All I am trying to do is print the factorials for numbers 0-30. When I run this, it endlessly prints Factorial=0. Can someone tell me how to correct this?
public static void factor(){
int n=0;
int factorial = 1;
while (n<=0&n<=30)
{
n=n++;
factorial = factorial * n;
n--;
System.out.println("Factorial = " + factorial);
}
}
public static void main(String[] args) {
factor();
}
You're decrementing n
inside the loop, so it it will always flip between 0
and 1
. Additionally, an int
can't hold numbers so large, and neither can a long
. You'll have to use something smarter, like a BigInteger
:
int n = 0;
BigInteger factorial = BigInteger.ONE;
while (n <= 30) {
System.out.printf("Factorial(%d) = %s%n", n, factorial);
n++;
factorial = factorial.multiply(BigInteger.valueOf(n));
}