Power Calculus
Time limit1sMemory limit128 MB
Find the minimum number of multiplications and divisions (using addition chains with subtraction allowed, keeping intermediate exponents positive) needed to build x^n for n up to 1000.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Math, Brute force
- Solved
- No attempts yet
Problem
Multiplying by thirty times yields :
If you are allowed to square an intermediate result, you can obtain in just operations:
If you also reuse earlier results by multiplying them together, can be reached in operations:
This is the most efficient way to obtain using multiplication only.
If division is also allowed, the number of operations can be reduced further: can be obtained with multiplications and division:
This is the most efficient way to compute when division is as fast as multiplication.
Write a program that, starting from , computes the minimum number of operations needed to build . Only the multiplication and division described above may be used. Every intermediate result must always be a positive power of ; that is, something like must never appear.
Input
The first line contains the number of test cases . Each test case consists of a single line containing an integer . is a positive integer less than or equal to .
Output
For each test case, output on its own line the minimum number of multiplications and divisions needed to build .