Java 对阶乘数组中的所有值求和并打印结果
我想写一个java程序,它将计算前20个阶乘并将它们存储在一个数组中。然后遍历数组,对所有项目求和,并在屏幕上打印结果 这是我的代码,但我认为我做错了什么:Java 对阶乘数组中的所有值求和并打印结果,java,arrays,math,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++){
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);
}
}
}
公共类数组问题4{
公共静态void main(字符串[]args){
长数组[]=新长数组[20];
长期温度=1;
for(int i=1;iLong
无法保存所有20!个结果的总和。Java中对“Long”有一个限制,它是
public static final long MAX_VALUE = 0x7fffffffffffffffL;
which is 9223372036854775807
使用“BigInteger”获得正确答案。同时,请参考“以说明代码可能没有执行您希望它执行的操作,请查看您通过(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,这是不正确的。定义n的阶乘的方法是
事实(n)=n*事实(n-1)
在解中,阶乘[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);
}
}
publicstaticvoidmain(字符串[]args){
长阶乘[]=新长[20];
//因为事实(1)=1*事实(0),事实(0)=1。
阶乘[0]=1;
对于(int n=1;n<20;n++){
//循环需要是什么问题?第一个递归不是阶乘的递归,第二个不是求和的递归。提示:你不需要任何temp
变量。但是你需要一个sum
变量。出来的数字不正确。来吧,人们解释我做错了什么,我只能每隔90问一个问题分钟。@jackzhang虽然我同情学习算法的困难,但我认为LutzL鼓励你在考虑了一个提示后自己寻找答案,因为这样做是一种更有效的学习方式。你只会得到这样的答案。20!=2432902008176640000,比9223372036少,854775807正如@DoubleDouble所说,在这种情况下,long将保留该值,尽管max value确实很快成为一个问题。这可能不会像K139所说的那样起作用。因此,使用BigInt和当前逻辑,如果发生这种情况,我只是在发布此消息后验证了这一点。如果有人决定使用更大的numb,我会将注释放在那里在循环外初始化第0个元素,在循环中初始化<20个比较,这也可能有帮助。
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);
}
}