I\'m trying program to calculate sequence of factorial numbers. ex) if n = 5 5!
ID: 3626657 • Letter: I
Question
I'm trying program to calculate sequence of factorial numbers.ex) if n = 5
5! + 4! + 3! + 2! + 1!
import java.util.Scanner;
public class practices {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Give n: ");
int n = input.nextInt();
double sum = 0.0;
int j = n-1;
do {
double fact = n;
for (int i = (n - 1); i > 0; i--) {
fact *= i;
}
sum += fact;
j--;
} while (j > 0);
System.out.println(sum);
}
}
This is what I have so far,,, Does anyone see what's wrong with the code?
Explanation / Answer
please rate - thanks
changing your as little as possible
import java.util.Scanner;
public class practices {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Give n: ");
int j = input.nextInt();
double sum = 0.0;
do {
double fact = j ;
for (int i = (j - 1); i > 0; i--) {
fact *= i;
}
sum += fact;
j--;
} while (j > 0);
System.out.println(sum);
}
}
--------------
how I would do it
import java.util.Scanner;
public class practices {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Give n: ");
int j = input.nextInt();
int fact=1;
double sum = fact;
for(int i=2;i<=j;i++)
{fact *= i;
sum += fact;
}
System.out.println(sum);
}
}