本文介绍了找到100阶乘用C数字之和不使用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关解决项目欧拉问题20找到的数字的总和在100分!我运行下面的程序,它正在为小数字的阶乘而不是100.which数据类型,我应该使用还是有必要使用数组用于存储数字?

  INT REC(INT);无效的主要()
{
    INT F = 1,I = 1,Z,S = 0,R,N;    而(I< = 100)
    {
        F = F * I;
        F = REC(F);
        我++;
    }
    N = F;    而(N!= 0)
    {
        R = N%10;
        N = N / 10;
        S = + Rs;
    }    的printf(\\ N%D,S);
}INT REC(INT T)
{
    如果(T%10 == 0)
    {
        T = T / 10;
        REC(T);
    }
    返回吨;
}


解决方案

您应该寻找溢出,每次迭代后打印的价值。

注意 REC(T); ,因为它不使用返回值没有做任何事情......你想要 T = REC(T);

INT 肯定是太短了,试试长长 ...如果仍然爆棚,你需要其他数据结构..如:GMP库

请注意:使用一些正确的语言作业可能会给你一些有识之士你必须支持的范围...例如使用Python:

 >>>进口数学
>>> math.factorial(100)
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000L

For solving project euler problem 20 to find the sum of digits in 100! i am running the following program , it is working for factorial of small numbers but not for 100.which data type should i use or is it necessary to use an array for storing the digits?

int rec(int);

void main()
{
    int f=1,i=1,z,s=0,r,n;

    while(i<=100)
    {
        f=f*i;
        f=rec(f);
        i++;
    }
    n=f;

    while(n!=0)
    {
        r=n%10;
        n=n/10;
        s=s+r;
    }

    printf("\n%d",s);
}

int rec(int t)
{
    if(t%10==0)
    {
        t=t/10;
        rec(t);
    }
    return t;
}
解决方案

You should look for overflow, print the value after each iteration.

Note that rec(t); doesn't do anything as it doesn't use the returned value... you want t = rec(t);.

int is definitely too short, try long long... if that's still overflowing, you need another data structure.. eg: GMP Library.

Note: using some "proper" language for the job might give you some insight to the range you have to support... e.g. with python:

>>> import math
>>> math.factorial(100)
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000L

这篇关于找到100阶乘用C数字之和不使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:44