• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Factorial Method printing a table  RSS feed

 
Lexi Turgeon
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Knute Snortum
Sheriff
Posts: 4270
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 4270
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!