【light-oj】-1189 - Sum of Factorials(思维,数学)

来源:互联网 发布:30岁程序员失业怎么办 编辑:程序博客网 时间:2024/05/21 10:36

1189 - Sum of Factorials
   PDF (English)StatisticsForum
Time Limit: 0.5 second(s)Memory Limit: 32 MB

Given an integer n, you have to find whether it can be expressed as summation of factorials. For given n, you have to report a solution such that

n = x1! + x2! + ... + xn! (xi < xj for all i < j)

Input

Input starts with an integer T (≤ 10000), denoting the number of test cases.

Each case starts with a line containing an integer n (1 ≤ n ≤ 1018).

Output

For each case, print the case number and the solution in summation of factorial form. If there is no solution then print 'impossible'. There can be multiple solutions, any valid one will do. See the samples for exact formatting.

Sample Input

Output for Sample Input

4

7

7

9

11

Case 1: 1!+3!

Case 2: 0!+3!

Case 3: 1!+2!+3!

Case 4: impossible



题意:把一个数写成n个数阶乘相加的形式。

题解:规律:一个数的阶乘总是大于等于前面数阶乘的和

把n写成几个数阶乘和的形式:若n>m!  n-=m!,继续判断m前的数,直到循环到达0后结束。

最后若n==0,就可以,否则不可以。

AC代码 1:

#include<cstdio> #include<cstring>#include<stack> #include<algorithm>using namespace std;#define LL long long LL n;LL fac[25];LL sum=1;void getfac(){fac[0]=1;for(int i=1;i<=19;i++){fac[i]=i*fac[i-1];sum+=fac[i]; }}int main(){getfac();int u,ca=1;scanf("%d",&u);while(u--){bool flag=false;stack<int> sk;scanf("%lld",&n);printf("Case %d: ",ca++);if(n>sum){printf("impossible\n");continue;}while(!sk.empty())sk.pop();for(int i=19;i>=0;i--){if(n<fac[i])continue;else if(n==fac[i]){sk.push(i);flag=true;break;}else if(n>2*fac[i])break;else{sk.push(i);n-=fac[i];}}if(!flag) printf("impossible\n");else{while(sk.size()!=1){printf("%d!+",sk.top());sk.pop();}printf("%d!\n",sk.top());sk.pop();}}return 0;}

AC代码 2:

#include<cstdio>#define LL long longLL fac[22];int a[22];int main(){int u,ca=1;scanf("%d",&u);fac[0]=1;for(int i=1;i<=19;i++)fac[i]=i*fac[i-1];while(u--){LL n;int k=1;scanf("%lld",&n);printf("Case %d: ",ca++);for(int i=19;i>=0;i--){if(n>=fac[i]){a[k++]=i;n-=fac[i];}}if(n==0){for(int i=k-1;i>1;i--)printf("%d!+",a[i]);printf("%d!\n",a[1]);}elseputs("impossible");}}


0 0
原创粉丝点击