Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Java Factorial Method printing a table

Ranch Hand
Posts: 156
Create a new project called BigIntegerFactorial and start by writing an iterative version of factorial (you should have created one for the Chapter 6 exercises). I have done this. My code will take the inputted number and give the value of the factorial of it, and this is what my code looks like:

My problem lies here:

Print a table of the integers from 0 to 30 along with their factorials. At some point around 13,
you will probably see that the answers are not right any more. Why not? Put a comment in
your code explaining the problem with this method.

How do I make this code so that it prints a table of the numbers 0 to 30 regardless of if they are correct or not?

Sheriff
Posts: 4748
131
Have you tried entering the numbers 0 through 30?  I think you will find that the answers will be wrong at some point with that code.

Lexi Turgeon
Ranch Hand
Posts: 156

Knute Snortum wrote:Have you tried entering the numbers 0 through 30?  I think you will find that the answers will be wrong at some point with that code.

Yes you were correct. I was hoping to print it in a table but I will skip that. Why don't they calculate the correct factorial beyond 12? (or around there)

Marshal
Posts: 58414
178
It is an overflow error. It is a standard problem with integer arithmetic. 12! will fit in the confines of an int, but 13! won't, so you get an incorrect result. Have you tried it with longs?

Lexi Turgeon
Ranch Hand
Posts: 156
I have it completely set up to work with BigInteger, I just was not sure why it did not work without BigInteger. Thank you!

Lexi Turgeon
Ranch Hand
Posts: 156
Actually, the BigInteger should be an iterative program that was formed from the above code. So is what I have iterative? I believe so. (I compared it to material given to me). Do you see anything missing/ am I possibly wrong?

Knute Snortum
Sheriff
Posts: 4748
131
It looks very good.  I have one minor comment: these lines

can be shortened to just table(30);

Okay, one more suggestion (minor): do you know for-loops?  I think a for-loop would work better than a while-loop in table().

 It is sorta covered in the JavaRanch Style Guide.