欧拉计划 -- Problem20

Project-Euler -- Problem20

我以为我解决了这个问题,但程序输出“0”。我看不出有什么问题。谢谢你的帮助。

问题:

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

For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!

package projecteuler;

public class problem20 {

    public static void main(String[] args) 
    {
        int sayi=0;
        int carpim=1;
        for(int i=100;i>=1;i--)
        {
            carpim*=i;  
        }
        String carp=""+carpim;
        int[] dizi = new int[carp.length()];
        String[] dizis=new String[carp.length()];

        for(int i=0;i<carp.length();i++)
        {
            dizis[i]=carp.substring(i);
        }

        for(int i=0;i<carp.length();i++)
        {
            dizi[i]=Integer.parseInt(dizis[i]);
            sayi+=dizi[i];
        }
        System.out.println(sayi);
    }
}   

100!93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 ,这超出了 int 的有效范围(相当多)。尝试使用 BigInteger。为了让你开始,

BigInteger carpim = BigInteger.ONE;
for (int i = 100; i >= 1; i--) {
    carpim = carpim.multiply(BigInteger.valueOf(i));
}
System.out.println(carpim);

输出就是前面提到的数字

看来人数溢出了。 https://ideone.com/UkXQ4e

4611686018427387904
-4611686018427387904
-9223372036854775808
-9223372036854775808
0
0
0

您可能想尝试不同的 class 作为阶乘,例如 BigInteger

在大学里,我得到了这个寻找 n 的例子!使用此 算法 。这是基于 n! = n * (n-1)! (例如,5!= 4 * 3!)。使用递归算法:

function factorial(n)
if (n = 0) return 1
while (n != 0)
return n * [factorial(n-1)]

一旦你有 100!,很容易将其解析为 String 并从中提取 Integers 以获得 sum

    int sum = 0;

    for (Character c : yourBigInteger.toString().toCharArray()) {
        sum = sum + Integer.parseInt(c.toString());
    }

    System.out.println(sum);

public static void descomposicionFactorial(int num) {

    BigInteger factorial = BigInteger.ONE;
    for (int i = num; i > 0; i--) {

        factorial = factorial.multiply(BigInteger.valueOf(i));
    }
    String aux =factorial.toString();
    char cantidad[] = aux.toCharArray();
    int suma = 0, numero = 0;
    for (int i = 0; i <cantidad.length; i++) {

        numero = cantidad[i] - '0';
        suma += numero;    
    }

    System.out.println(suma);
}