public static void main(string[] args) { int n = factorial(30); int x = 0; while (x <= 30) { system.out.println(x + " " + n); x = x + 1; } public static int factorial (int n) { if (n == 0) { return 1; } else { return n * factorial (n-1); } } }
i'm trying print out this:
0 1 1 1 2 2 3 6 4 24 ...etc, 30 (30!)
what i'm getting instead this:
0 (30!) 1 (30!) ...etc, 30
in words, i'm able create left column 0 30 want make print factorial of numbers in right hand column. code, prints factorial of 30 in right-hand column. want print factorials in order next corresponding number. how can fix code this?
this pretty simple. instead of defining variable, call method updated x
every time:
system.out.println(x + " " + factorial(x));
note loop rewritten for
loop, they're designed for:
for (int x = 0; x < 30; x++) { system.out.println(x + " " + factorial(x)); }
note couple of things:
- the
x++
. it's short form ofx = x + 1
, though there caveats. see this question more information that. x
defined in loop (for (int x = ...
) not before itn
never defined or used. rather setting variable that's used once, directly used result offactorial(x)
.
note: i'm pretty int
overflow when confronted 30!. 265252859812191058636308480000000 pretty big number. overflows long
, turns out. if want handle properly, use biginteger
:
public biginteger factorial(int n) { if (n == 0) { return biginteger.one; } else { return new biginteger(n) * factorial(n - 1); } }
because of biginteger#tostring()
's magic, don't have change in main
make work, though still recommend following advice above.