One way to solve this problem is to add a count to the modular exponentiation routine given in class,
but I'd like to discuss another way of counting the number of multiplications.
First, I want to observer that when a number is represented in binary,
it's easy to tell if it's odd or even.
All you have to do is look at the last digit.
For example, 10 is 1010, a 11 is 1011.
Dividing by 2 is a shift right.
For example, 20 to 10 to 5 is shift and then another shift.
In our modular exponentiation routine, if our exponent is even, we divide by 2.
It costs 1 multiplication.
If our exponent is odd, we subtract 1 from it,
which will make it even, and then we divide by 2.
If our exponent is odd, it costs 2 multiplications.
From this, we can easily see that for every 1 in the exponent when written in binary,
we do two multiplications, and for every 0 we do only do one multiplication.
Writing our four exponents in binary, where 1023 is--that should hopefully be ten 1s--
gives us a cost of 20; 1015 has a cost of 13; 4096--
which should be 1 followed by hopefully 12 zeros--gives a cost of 14;
and 4097 gives a cost of 15.
So 1023 is out most expensive operation, and that is our correct answer.
