Find the sum of digits in n!

Find the sum of digits in n!

 

Time Limit:   2000MS       Memory Limit:   65535KB
Submissions:   192       Accepted:   41

 

Description

 

n! means n * (n − 1) * ... * 3 * 2 * 1

Find the sum of the digits in the number n!

 

Input

one line: n (1<n<=10000)

Output

the sum of the digits in the number n!

Sample Input

10

Sample Output

27
Hint

10! = 3628800

3+6+2+8+8+0+0 = 27

【分析】

这道题如果用第一种方法,会超时

那还是用“万进制”吧!

如果哪位读者还有好方法,希望留评论,一起讨论,谢哈!!

# include<stdio.h>
# include<string.h>
int str[10000];
int solve(int n)
{
    int w=1,sign,i,j,leap;
    str[0]=1;
    
    for(i=1;i<=n;i++)
    {
        sign=0;
        for(j=0;j<w;j++)
        {
            leap=str[j];
            str[j]=(leap*i+sign)%10000;//用“万进制”的四位数
            sign=(leap*i+sign)/10000;//类似十进制进位
        }
        if(sign)
        {
         w++;
           str[j]=sign;
           sign=0;
        }
    }
    return w;
}
int main()
{
    int num,i,j,sum;
    scanf("%d",&num);
    sum=0;
    memset(str,0,sizeof(str));
    j=solve(num);
    for(i=j-1;i>=0;i--)//这里注一下,str[i]可能不是一位数,需要取出每一位
    {
       while(str[i])
       {
           sum+=str[i]%10;
        str[i]/=10;
       }
    }
        printf("%d\n",sum);
    return 0;
}

 

posted on 2012-05-22 19:20  即为将军  阅读(342)  评论(0)    收藏  举报

导航