Project-Euler — Problem20

佐手、 提交于 2019-12-13 08:17:45

问题


I thought I solved this problem but the program output "0". I don't see any problem. Thank you for helping.

Question :

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);
    }
}   

回答1:


100! is 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 , and that exceeds the valid range of an int (by rather a lot). Try using a BigInteger. To get you started,

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

The output of which is the number mentioned before.




回答2:


It appears the number is overflowing. https://ideone.com/UkXQ4e

4611686018427387904
-4611686018427387904
-9223372036854775808
-9223372036854775808
0
0
0

You might want to try a different class for the factorial like BigInteger




回答3:


In college, I got this example for finding n! using this algorithm. this is based on the fact that n! = n * (n-1)! (for example, 5! = 4 * 3!). Using a recursive algorithm:

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

once you have 100!, its easy to parse it as String and make Integers out of it to get the sum

    int sum = 0;

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

    System.out.println(sum);



回答4:


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);
}


来源:https://stackoverflow.com/questions/28206158/project-euler-problem20

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!