Lotteries revisited
No. 106
Q: |
Wrap your implementation from the section called “Loops and calculations” into a single method
Manually calculate and beforehand to add more unit tests. Your implementation is likely to fail for (at least) one of these. Why does this happen? May you propose a solution? Keep in mind the idea to deal with “6 out of 90” lottery situations. TipBe careful about possible arithmetic overflows. |
||||||||
A: |
This actually wraps Equation 1, “Calculating binomials by cancelling common
factors.” into a method
What happens when calculating ?
In this case our numerator variable of type
So This does not show up as an error since exactly the same (mis)calculation happens for the denominator. Thus their quotient by coincidence returns a correct value of 1. This however is no longer true when examining . We may still get correct results in many situations including the given example. If k gets too large we may use: So instead of calculating we take its sibling of identical value:
Finally our lottery code from the section called “Loops and calculations” gets a little bit simplified:
|