Recitation: While Loops

Exercise 1: population increase

You are studying two populations A and B. You know that population A is initially smaller than population B, but it grows at a faster rate. You would like to know haw many days it would take for population A to overtake population B. Luckily you have taken 15-110, and you know it would be faster to sit down and implement a program to compute that for you, than having to do the math each time (you work with a lot of populations of many different organisms...).

Implement the function populationIncrease(pa, pb, ga, gb) that takes as parameters:

This function should return the number of days it takes for population A to overtake population B.

Important: Populations grow by an integer number of individuals. So if the growth rate is 3.6% and the population is 100, in one day there will be 103 (not 103.6) individuals. If the population is 1000, there will be 1036 individuals.

Exercise 2: Next lucky number

We’ll say that an integer is a lucky number (coined term) if one of its digits is 7.

Some examples of lucky numbers are: 7, 17, 712, 10007.

Some numbers that are not lucky are: 6, 15110, 42 (no sevens at all),

Implement the function nextLuckyNumber(n) that returns the first lucky number bigger than n (not including n). For example, nextLuckyNumber(3) should return 7, and nextLuckyNumber(67) should return 70.

Exercise 3: Convert to Binary (challenge)

Numbers are represented in a binary system by using their representation in base-2. To understand this representation, we will look at the one we usually use, in base-10, and generalize from there. You might not realize every time you read a number, but here's what's actually going on:

$$ \begin{array}{rl} 42 &= 4 \times 10 + 2 \times 1 \\ &= 4 \times 10^1 + 2 \times 10^0 \end{array} $$

Our numbers are a combination of powers of $10$ multiplied by a coefficient, and their representation is simply these coefficients put together in a certain order: starting from $0$, concatenate them from right to left until the last non-zero coefficient. These coefficients range from $0$ to $9$, can you guess why?

This same idea can be applied to any natural number, not only $10$. The next most popular bases are $2$ (binary) and $16$ (hexadecimal).

Let's apply the same idea to a number in binary (this time the number on the left of $\equiv$ is in base $2$ and the number on the right is in base $10$):

$$ \begin{array}{rl} 11001 &\equiv 1 \times 2^4 + 1 \times 2^3 + 0 \times 2^2 + 0 \times 2^1 + 1 \times 2^0 \\ &\equiv 16 + 8 + 1 \\ &\equiv 25 \end{array} $$

Hence all numbers can be represented in a binary system.

Write the function toBinary(n) that takes an integer number n and returns its the binary representation as an integer containing only ones and zeroes.

For example:

Starter code