this question is related to this post: https://stackoverflow.com/a/35810542/5888956
Basically, I have to write a program that reads in the integer from the keyboard, and it has to be able to display 50! using only array. (cannot use Biginteger or anything) I got this so far, thanks to the help from the previous post.
import java.util.Scanner;
class Factorial
{
public static void main(String[] args)
{
int n;
Scanner kb = new Scanner(System.in);
System.out.println("Enter n");
n = kb.nextInt();
int [] result = fact(n);
int i = result.length-1;
while (i > 0 && result[i] == 0)
{
i--;
}
System.out.print(n + "! = ");
while (i >= 0)
{
System.out.print(result[i--]);
}
System.out.println();
}
public static int[] fact(int n)
{
int[] a = new int[100];
a[0] = 1;
for (int i = 1; i <= n; i++)
{
int carry = 0;
for(int j = 0; j < a.length; j++)
{
int x = a[j] * i + carry;
a[j] = x % 10;
carry = x / 10;
}
}
return a;
}
}
But I can't still understand the logic behind here. Especially, this part,
for (int i = 1; i <= n; i++)
{
int carry = 0;
for(int j = 0; j < a.length; j++)
{
int x = a[j] * i + carry;
a[j] = x % 10;
carry = x / 10;
}
}
I'm trying to solve this with pen and paper, so that I can understand it completely. (of course with the small number like 4!)
So if I type 4 for n, 4! is 24 (4*3*2*1).
In my logic, when i
is 1
a[0]
is 1
because I initialized above, but after the for loop ends once, does it become 0
?
i = 1, j = 0
x = a[0] * 1 + 0 = 1
a[0] = 0
carry = 1
// ------repeat the loop
i = 2, j = 0
x = a[0] * 1 + 1 = 1
a[0] = 0
carry = 1
So it is apparently not the right logic, I think. Can someone please please help me to understand this?