題目來源:http://acm.hdu.edu.cn/showproblem.php?pid=2212
Problem Description
A DFS(digital factorial sum) number is found by summing the factorial of every digit of a positive integer.
For example ,consider the positive integer 145 = 1!+4!+5!, so it’s a DFS number.
Now you should find out all the DFS numbers in the range of int( [1, 2147483647] ).
There is no input for this problem. Output all the DFS numbers in increasing order. The first 2 lines of the output are shown below.
問題描述
通過對正整數的每個數字的階乘求和來找到DFS(數字階乘和)數。
例如,考慮正整數145 = 1!+4!+5 !,因此它是DFS編號。
現在你應該找到int([1,2147483647])範圍內的所有DFS數字。
這個問題沒有輸入。按遞增順序輸出所有DFS編號。輸出的前兩行如下所示。
輸入
沒有輸入
輸出
以遞增順序輸出所有DFS編號。
分析:
1.循環從1開始
2.範圍是[1,2147483647] ,該範圍內最大的階乘和爲9個9 其和爲3265920 所以只需要遍歷到3265920 即可
3.0的是1
樣本輸出
1
2
…
作者
ZJT
運行代碼:
1.普通方法:
#include<Stdio.h>
#include<String.h>
#include<math.h>
int main()
{
long long i,n[15],num,j,t,value,c;
for(int i=1;i<=3265920;i++) //該範圍內最大的階乘和爲9個9 其和爲3265920 所以只需要遍歷到3265920 即可
{
t=i; //方便最後的比較
num=0; //數字位數
value=0; //階乘和
while(t) //t=0 退出
{
n[num]=t%10; //獲取每位上數字
if(n[num]==0) //判斷每位上數字是不是0
value+=1; //是0的話 階乘和+1
else //不是的話 正常計算即可
{
c=1;
for(j=1;j<=n[num];j++)//獲得該數的階乘
c*=j;
value+=c;
}
t/=10; //爲了獲取下一位數字
num++;
}
if(i==value) //如果是DFS
printf("%d\n",i);
}
return 0;
}
2.dfs
#include<Stdio.h>
#include<String.h>
#include<math.h>
int dfs(int m)
{
long long n[15],num,j,t,value,c;
if(m>3265920)//該範圍內最大的階乘和爲9個9 其和爲3265920 所以只需要遍歷到3265920 即可
return 0;
t=m; //方便最後的比較
num=0; //數字位數
value=0; //階乘和
while(t) //t=0 退出
{
n[num]=t%10; //獲取每位上數字
if(n[num]==0) //判斷每位上數字是不是0
value+=1; //是0的話 階乘和+1
else //不是的話 正常計算即可
{
c=1;
for(j=1;j<=n[num];j++)//獲得該數的階乘
c*=j;
value+=c;
}
t/=10; //爲了獲取下一位數字
num++;
}
if(m==value) //如果是DFS
printf("%d\n",m);
dfs(++m);
}
int main()
{
dfs(1);
return 0;
}
運行結果:
總結:
如果遍歷到2147483647,則時間超限。該題也要注意0的階乘是1.