recently I found an interesting task given in a competition, but without any author solution or explanation how to be solved.
The task consists of the following: The user is given a number N, and has to calculate a^N
(on the power of n, not the xor operation), where I can only calculate by multiplying by a, or by a previous result. I should give the smallest number of calculations I should do in order to get calculate a^n
.
Example:
N=27
Then the answer is 6:
a^2=a*a
a^3=a^2*a
a^6=a^3*a^3
a^9=a^3*a^6
a^18=a^9*a^9
a^27=a^18*a^9
The limits for N are the following: N<=40000
. The time and memory limits are: 2s and 256MB
.
What is a good way to solve this task?
Thank you in advance!!!