|
Non-Programming Exercises:
// mult: inputs X and Y both > 0 int mult(int X, int Y) { int x = X, y = Y, p = 0; while (y > 0) { p = p + x; y = y - 1; } return p; }
The inputs are
The algorithm calculates and returns
such that
Here is the picture:
q +------- d | n -----+ ------ r
Here is the function:
// div: inputs n >= 0 and d >= 1, returns the pair (q, r) (int, int) div(int n, int d) { int q = 0, r = n; while (r >= d) { q = q + 1; r = r - d; } return (q, r); }
The loop invariant is:
n = q * d + r
Carefully write out the four steps similar to those given in the lecture notes under XI.4 a-d (for exponentiation in the notes).
x*u[0] + y*u[1] = u[2] x*v[0] + y*v[1] = v[2] x*t[0] + y*t[1] = t[2]
This question asks you to prove two parts of using the loop invariant to show that the algorithm works.
t[0] = u[0] - v[0]*q; t[1] = u[1] - v[1]*q; t[2] = u[2] - v[2]*q;
With these newly calculated values of the array t, and assuming the first two loop invariant equations are true, show that the third loop invariant equation is true, that is, show that:
x*t[0] + y*t[1] = t[2]
It is easier to calculate the probability that among
n people, no two have the same
birthday. Denote this by N(n).
For two people, the second one will have a birthday different
from the first with probability:
N(2) = 364/365.
If there is a third person
the probability that he will have a birthday different from
the first two (which are assumed distinct now),
is 363/365, so that
N(3) = (364/365)*(363/365).
Similarly,
N(4) = (364/365)*(363/365)*(362/365).
Of course, N(1) = 1.
The probability, call it S(n), that at least two
people from among n have the same birthday
is just:
S(n) = 1 - N(n).
Write a simple program that will calculate and print S(n) for n = 1, 2, 3, ..., 50. These should be calculated as doubles.