programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

A quiz for the bored

Rooks Forgenal
Ranch Hand
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?

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

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

************************************ 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
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
duly impressed sir/maam. duly impressed.

Nisha Ganeriwal
Greenhorn
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
Posts: 82
Like this?

Rooks Forgenal
Ranch Hand
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.