对因子数组中的所有值求和并打印结果

时间:2015-05-04 17:36:19

标签: java arrays math

我想写一个java程序,它将计算前20个阶乘并将它们存储在一个数组中。然后浏览数组并汇总所有项目并在屏幕上打印结果。

这是我的代码,但我认为我做错了什么:

public class ArrayQuestion4 {

    public static void main(String[] args) {
        long array[]= new long[20];
        long temp=1;

        for ( int i=1; i<20; i++){
            temp = i*(i+1);
            temp = temp*(temp+1);
            array[i]=temp;
            System.out.println(array[i]);
        }

        for ( int i=1; i<20; i++){
            temp = array[i];
            temp = array[i]+(array[i+1]);
            temp = temp+(temp+1);
            System.out.println(temp);
        }       
    }
}

顺便说一句,答案是不正确的。

我认为正确的代码是这样的:

public class ArrayQuestion4 {

public static void main(String[] args) {
    long array[]= new long[20];
    array[0]=1;
    long temp=0;
    for ( int i=1; i<20; i++){
        array[i]=array[i-1]*(i+1);
        System.out.println(array[i-1]+"*"+(i+1)+" = "+array[i]);
    }   

    for ( int i=1; i<20; i++){
       temp = temp + array[i-1] + array[i];
    }   
    System.out.println(" ");
    System.out.println("Sum = "+temp);
}
}

3 个答案:

答案 0 :(得分:1)

为了说明代码可能没有按照您希望的方式执行,请查看(2)的内容!

temp = i*(i+1);       //temp = 1*(1+1); which is 2
temp = temp*(temp+1); //temp = 2*(2+1); which is 6
array[i] = temp;      //array[1] = 6; - also note we skip ever assigning array[0]

你得到6作为答案,这是不正确的。

答案 1 :(得分:1)

定义n的阶乘的方式是 事实(n)= n *事实(n-1)

在解决方案中,factorial [n]表示阶乘(n)。 和temp是当前计算的阶乘。

public static void main(String[] args) {

    long factorial[] = new long[20];
    //Because Fact(1) = 1 * Fact(0), and fact(0) = 1.
    factorial[0] = 1;

    for (int n = 1; n < 20; n++) {
        // Loop needs to be <20 because i have defined the array size = 20.            
        // <= would get an array out of bound exception. You can change the limits as you want.

        //calculating  the factorial based on formula:
        // Factorial(N) = n * Facorial(N-1);
        long factorialOfN = n*factorial[n-1];

        //storing back the value in the array for future use.
        factorial[n] = factorialOfN;

       //Printing it.
        System.out.println(factorialOfN);
    }
}

答案 2 :(得分:0)

Long无法容纳所有20个的总和!结果。 Java中的'long'有一个限制,它是

 public static final long MAX_VALUE = 0x7fffffffffffffffL;

 which is 9223372036854775807

使用'BigInteger'获得正确答案。另请参阅“How (not) to write Factorial in Java