Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A quiz for the bored

 
Rooks Forgenal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It the making of these functions, I ran across an interesting error that I bet beginners run into a LOT!
Why is the "BAD" function going to produce trash and the "GOOD" section fine?
************************************ BAD ************************************

************************************ GOOD *************************************

The recursive version of this question is this: This is easier to see but harder to understand.
************************************ BAD **************************************

************************************ GOOD *************************************

if you are wondering why I did not put:
in the recursive one, it is because I couldn't figure out precisely where I would put it and what the effect would be in the recursion.
 
Nisha Ganeriwal
Greenhorn
Posts: 8
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the "bad" methods, when you write: answer = answer * ((n - i) / (i + 1)); , in the division, you loose precision because when you divide int by int the result is an int and the remainder is lost. But this does not happen in the "good" methods as there the answer*(n-i) is calculated first which is always perfectly divisible by (i+1).

 
Rooks Forgenal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
duly impressed sir/maam. duly impressed.
 
Nisha Ganeriwal
Greenhorn
Posts: 8
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the recursive methods, you can store the value returned by nCr_recursive(..) in a variable, compare it with 0 and throw the exception.
 
Rooks Forgenal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like this?
 
Rooks Forgenal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Turns out GOOD is not so good after all. As a result of reading every output, I found an error in the algorithm when nCr(30,15) is submitted. Can anyone see the error?
As a hint, here is how I fixed it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic