POJ 1775 、 FZU 1106 Sum of Factorials
题目:
Description
Input
Output
Sample Input
9 -1
Sample Output
YES
这个题目是考1个性质:
当n>1时,0!+1!+2!+......+n!<(n+1)!,当n=1时,0!+1!=2!,当n=0时,0!=1!
任取一个递增的函数f(x)满足下述条件:当x为整数时,f(x)=x!
用g表示f的反函数,那么这个算法的时间复杂度为θ(g(n))
比如说,本题n约为10!,那么大约有10次运算
(我这个描述其实是不准确的,因为有常数的问题。
准确的说法应该是,这个算法有大约g(n)次运算,常数为1)
代码:
#include<iostream> using namespace std; int fac[10] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; int main() { int n; while (cin >> n) { if (n < 0)break; if (n == 0)cout << "NO"; else { for (int i = 9; i >= 0; i--)if (n>=fac[i])n -= fac[i]; if (n == 0)cout << "YES"; else cout << "NO"; } cout << endl; } return 0; }
LightOJ 1189 Sum of Factorials
题目:
Description
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
4
7
7
9
11
Sample Output
Case 1: 1!+3!
Case 2: 0!+3!
Case 3: 1!+2!+3!
Case 4: impossible
题目差不多,代码稍微改下就可以了。
代码:
#include<iostream> #include<stack> using namespace std; long long fac[20] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800,87178291200, 1307674368000, 20922789888000, 355687428096000, 6402373705728000, 121645100408832000 }; stack<int>s; int main() { int t; cin >> t; long long n; for (int cas = 1; cas <= t; cas++) { cin >> n; cout << "Case " << cas << ": "; while (!s.empty())s.pop(); for (int i = 19; i >= 0; i--)if (n >= fac[i]) { n -= fac[i]; s.push(i); } if (n == 0) { while (!s.empty()) { n = s.top(); s.pop(); cout << n << '!'; if (!s.empty())cout << '+'; } } else cout << "impossible"; cout << endl; } return 0; }