Loops and calculations
|
1 + ... + 5 = 15 |
No. 77
Display all summands
Q: |
In Figure 176, “Calculating values ” for a
given value of limit only the first and last summand will show
up: We just see If 1 + ... + 1 = 1 Modify the code accordingly to print the above TipUsing |
A: |
A first approach reads:
This is close to the intended output. However our sum ends with an excess trailing “+” symbol: 1 + 2 + 3 + 4 + 5 + = 15 We get rid of it by introducing an final int LIMIT = 5; for (int i = 1; i <= LIMIT; i++) { System.out.print(i); if (i < LIMIT) { // Avoid '+' for the very last value System.out.print(" + "); } sum += i; } System.out.println(" = " + sum); This avoids the trailing “+”: 1 + 2 + 3 + 4 + 5 = 15 Moreover it works for 1 = 1 Instead of filtering the very last “
|
No. 78
Playing lottery
Q: |
Common lotteries randomly draw numbers from a given set like:
This category of lottery does not care about ordering (apart from so called jolly numbers). The number of possibilities for drawing k out of n numbers ignoring their ordering is being given by the binomial coefficient : Write an application which allows for determining the probabilistic success rates using this coefficient. For the German „Glücksspirale“ a possible output reads: Your chance to win when drawing 6 out of 49 is 1 : 13983816 Store parameters like 6 or 49 in variables to keep your software flexible. Tip
|
||||
A: |
Consider the following snippet:
This results in: 1! == 1 2! == 2 3! == 6 4! == 24 5! == 120 6! == 720 7! == 5040 8! == 40320 9! == 362880 10! == 3628800 11! == 39916800 12! == 479001600 13! == 1932053504 ... 49! == 0 Only results up to
are correct: The next term
equals 6227020800 which is ways beyond
1! == 1 2! == 2 3! == 6 4! == 24 5! == 120 6! == 720 7! == 5040 8! == 40320 9! == 362880 10! == 3628800 11! == 39916800 12! == 479001600 13! == 6227020800 14! == 87178291200 15! == 1307674368000 16! == 20922789888000 17! == 355687428096000 18! == 6402373705728000 19! == 121645100408832000 20! == 2432902008176640000 21! == -4249290049419214848 ... 49! == 8789267254022766592 This time Fortunately we have another option. Consider an example: We generalize this fraction cancellation example: Equation 1. Calculating binomials by cancelling common
factors.
And thus: We calculate numerator and denominator in two separate loops:
|