Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 13792 | Accepted: 4537 |
Description
There are some numbers which can be expressed by the sum of factorials. For example 9,9=1!+2!+3! Dr. von Neumann was very interested in such numbers. So, he gives you a number n, and wants you to tell him whether or not the number can be expressed by the sum of some factorials.
Well, it's just a piece of cake. For a given n, you'll check if there are some xi, and let n equal to Σ 1<=i<=tx i!. (t >=1 1, xi >= 0, xi = xj iff. i = j). If the answer is yes, say "YES"; otherwise, print out "NO".
Input
The input is terminated by a line with a negative integer.
Output
Sample Input
9 -1
Sample Output
YES
Source
Regionals 2003 >> Asia - Guangzhou
问题链接:UVALive2953 POJ1775 ZOJ2358 Sum of Factorials。
问题简述:输入非负整数n,问能否表示成若干个阶乘之和。
问题分析:
对于输入的n(n <= 1,000,000),如果能够表示成若干个阶乘之和,那么最大的阶乘是多少呢?这需要编写一段程序(函数output_fact())计算一下,结果如下:
0! fact=1 sumfact=1
1! fact=1 sumfact=2
2! fact=2 sumfact=4
3! fact=6 sumfact=10
4! fact=24 sumfact=34
5! fact=120 sumfact=154
6! fact=720 sumfact=874
7! fact=5040 sumfact=5914
8! fact=40320 sumfact=46234
9! fact=362880 sumfact=409114
10! fact=3628800 sumfact=4037914
从上述结果看,和的最大的部分只能是9!。这样事情就简单了,对于输入的n穷尽搜索(从大到小搜索)就可以了。
阶乘值事先打表是必要的,可以避免重复计算。
参考链接:(略)
/* UVALive2953 POJ1775 ZOJ2358 Sum of Factorials */
#include <iostream>
#include <stdio.h>
using namespace std;
const int N = 10;
int fact[N+1];
void output_fact(int n)
{
int fact = 1, sumfact = 0;
for(int i=0; i<=n; i++) {
if(i>0)
fact *= i;
sumfact += fact;
printf("%d! fact=%d sumfact=%d\n", i, fact, sumfact);
}
}
void setfact(int n)
{
fact[0] = 1;
for(int i=1; i<=n; i++)
fact[i] = fact[i - 1] * i;
}
int main()
{
// output_fact(N);
setfact(N);
int n;
while(~scanf("%d", &n) && n >= 0) {
if(n==0) {
printf("NO\n");
} else {
for(int i=N-1; i>=0; i--)
if(n >= fact[i])
n -= fact[i];
if(n == 0)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}