### Efficient exponentiation题号：122 难度： 40 中英对照

The most naive way of computing n15 requires fourteen multiplications:

n × n × ... × n = n15

But using a "binary" method you can compute it in six multiplications:

n × n = n2
n2 × n2 = n4
n4 × n4 = n8
n8 × n4 = n12
n12 × n2 = n14
n14 × n = n15

However it is yet possible to compute it in only five multiplications:

n × n = n2
n2 × n = n3
n3 × n3 = n6
n6 × n6 = n12
n12 × n3 = n15

We shall define m(k) to be the minimum number of multiplications to compute nk; for example m(15) = 5.

For 1 ≤ k ≤ 200, find m(k).

### Code



public final class p122 {
public static void main(String[] args) {
long start=System.nanoTime();
String result = run();
long end=System.nanoTime();
System.out.println(result);
System.out.println( (end-start)/1000000 + "ms" );
}
static final int limit=200;
static int m[]=new int[limit+1];//答案
static int data[]=new int[limit+1];//树上的节点

static public String run(){
for(int i=0;i<limit+1;i++)
m[i]=Integer.MAX_VALUE;
solve(1,0);//把1放在树根上，其深度为0
int ans=0;
for(int i=1;i<=limit;i++){
ans+=m[i];
}
return ""+ans;
}

static public void solve(int x, int depth) {
if (x > limit || depth > m[x]) return;
m[x] = depth;
data[depth] = x;
for (int i = depth; i >= 0; i--)
solve(x + data[i], depth + 1);
}

}
1582
6ms