Power Calculus

Time limit1sMemory limit128 MB

Summary
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 xx by xx thirty times yields x31x^{31}:

x2=x×x,x3=x2×x,x4=x3×x,…,x31=x30×xx^2 = x \times x,\quad x^3 = x^2 \times x,\quad x^4 = x^3 \times x,\quad \dots,\quad x^{31} = x^{30} \times x

If you are allowed to square an intermediate result, you can obtain x31x^{31} in just 88 operations:

x2=x×x,x3=x2×x,x6=x3×x3,x7=x6×x,x14=x7×x7,x15=x14×x,x30=x15×x15,x31=x30×xx^2 = x \times x,\quad x^3 = x^2 \times x,\quad x^6 = x^3 \times x^3,\quad x^7 = x^6 \times x,\quad x^{14} = x^7 \times x^7,\quad x^{15} = x^{14} \times x,\quad x^{30} = x^{15} \times x^{15},\quad x^{31} = x^{30} \times x

If you also reuse earlier results by multiplying them together, x31x^{31} can be reached in 77 operations:

x2=x×x,x4=x2×x2,x8=x4×x4,x10=x8×x2,x20=x10×x10,x30=x20×x10,x31=x30×xx^2 = x \times x,\quad x^4 = x^2 \times x^2,\quad x^8 = x^4 \times x^4,\quad x^{10} = x^8 \times x^2,\quad x^{20} = x^{10} \times x^{10},\quad x^{30} = x^{20} \times x^{10},\quad x^{31} = x^{30} \times x

This is the most efficient way to obtain x31x^{31} using multiplication only.

If division is also allowed, the number of operations can be reduced further: x31x^{31} can be obtained with 55 multiplications and 11 division:

x2=x×x,x4=x2×x2,x8=x4×x4,x16=x8×x8,x32=x16×x16,x31=x32÷xx^2 = x \times x,\quad x^4 = x^2 \times x^2,\quad x^8 = x^4 \times x^4,\quad x^{16} = x^8 \times x^8,\quad x^{32} = x^{16} \times x^{16},\quad x^{31} = x^{32} \div x

This is the most efficient way to compute x31x^{31} when division is as fast as multiplication.

Write a program that, starting from xx, computes the minimum number of operations needed to build xnx^n. Only the multiplication and division described above may be used. Every intermediate result must always be a positive power of xx; that is, something like x−3x^{-3} must never appear.

Input

The first line contains the number of test cases TT. Each test case consists of a single line containing an integer nn. nn is a positive integer less than or equal to 10001000.

Output

For each test case, output on its own line the minimum number of multiplications and divisions needed to build xnx^n.

Examples1

  1. Example 1

    Input
    8
    1
    31
    70
    91
    473
    512
    811
    953
    
    Expected output
    0
    6
    8
    9
    11
    9
    13
    12