This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programming Diversions and the fly likes A quiz for the bored Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Other » Programming Diversions
Bookmark "A quiz for the bored" Watch "A quiz for the bored" New topic
Author

A quiz for the bored

Rooks Forgenal
Ranch Hand

Joined: Jun 05, 2009
Posts: 82
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

Joined: Feb 25, 2010
Posts: 8

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

Joined: Jun 05, 2009
Posts: 82
duly impressed sir/maam. duly impressed.
Nisha Ganeriwal
Greenhorn

Joined: Feb 25, 2010
Posts: 8

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

Joined: Jun 05, 2009
Posts: 82
Like this?
Rooks Forgenal
Ranch Hand

Joined: Jun 05, 2009
Posts: 82
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.
 
Consider Paul's rocket mass heater.
 
subject: A quiz for the bored
 
Similar Threads
exception
Question on sum of syracuse sequence (memorization question)
Fibonacci Algorithms and their different manifestations. Which is the best?
Using Postfix notation......
my brand spanking new layout manager