I have this question for homework: Write a program to calculate the sum of the factorials of the first n positive integers. This is what I have done so far but I am not getting the output that I should get. Can someone tell me what have I done wrong.
System.out.print("Enter a number: ");
int num=input.nextInt();
for (int i=1; i<=num; i++) {
num=num+i;
}
System.out.print(num);
I suggest this, for example:
public static void main(String... args){
int n=10;
BigInteger j=BigInteger.valueOf(1);
BigInteger k=BigInteger.valueOf(0);
for(int i=0;i<n;i++){
j=j.multiply(BigInteger.valueOf(i+1));
k=k.add(j);
//System.out.println(j + "\t" + k);
}
System.out.println("Sum of " + n + " first factorials equals: " + k);
}
I hope it helps.
Try this:
int n, c, fact = 1;
do {
System.out.println("Please enter a positive integer.");
n = input.nextInt();
} while ( n < 1 );
for ( c = 1 ; c <= n ; c++ ) {
fact = fact*c;
}
System.out.println("Factorial of "+n+" is = "+fact);
}
The do-while loops asks the user for an input, and repeats, if the input is smaller then 1. Furthermore your line to calculate the factorial is not correct, I guess.
Note: This example does not prevent a "wrong" input like 12.5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.