The question is given in the following picture:
I solved it and my answer was B, but the answer sheet said that the answer is C as you can see from the following picture:
I do not know why, could anyone clarify this for me please?
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It only takes a minute to sign up.
Sign up to join this communityThe question is given in the following picture:
I solved it and my answer was B, but the answer sheet said that the answer is C as you can see from the following picture:
I do not know why, could anyone clarify this for me please?
Let us consider how $(k,i,p)$ changes. You get
$$(999,1,0)\rightarrow(999,2,1)\rightarrow(999,4,2)\rightarrow(999,8,3)\rightarrow...$$
It's clear $p=2$ isn't the answer. In fact, notice that the loop just doubles $i$ and increments $p$ until $i=2^{10}\ge999>2^9$ when the loop will exit and print $p$. Notice also, that $(k,i,p)=(999,2^{p},p)$.
Hence $p=10$ when the loop exits.
Have you tried actually following those instructions as you were told to do?
Initially, k= 999, i= 1 and p= 1. Since 999> 1, we do step 3: i becomes 2i= 2 and p becomes 1+ 1= 2.
Go back to step 2: i= 2< 999 so we do step 3: i becomes 2i= 4 and p becomes 2+ 1= 3.
Go back to step 2: i= 4< 999 so we do step 3: i becomes 2i= 8 and p becomes 3+ 1= 4.
That should be enough to convince you that i is being multiplied by 2 every time so after n repetitions $i= 2^n$. And p has 1 added every time so after n steps, p= 1+ n.
Now how many times do we repeat? We repeat until $2^n< 999$. You could determine n using logrithms if you have a calculator: if $2^n= 999$ then n log(2)= log(999). 0.3010n= 2.9996. n= 2.9996/0.3010= 9.9653. Since n must be an integer, n= 10. But we want $2^n< 999$, not equal to it so n= 10- 1= 9.
Or we could just do the doubling: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024. The last power of 2 less than 999 is $2^{9}= 512$.
Since n= 9, p= n+ 1= 10.
With each execution of the loop: the value of $i$ doubles and $p$ increases by $1$. Observe that $i$ is taking values as powers of $2$ and the power is reflected in $p$. The first time $i=2^p >1000$ is when $p=10$.