最少乘法次数

描述

给你一个非零整数,让你求这个数的n次方,每次相乘的结果可以在后面使用,求至少需要多少次乘。如24:2*2=22(第一次乘),22*22=24(第二次乘),所以最少共2次;

               

 
输入
第一行m表示有m(1<=m<=100)组测试数据;
每一组测试数据有一整数n(0<n<=10000);
输出
输出每组测试数据所需次数s;
样例输入
3
2
3
4
样例输出
1
2
2

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner scanner=new Scanner(System.in);
 6         int T;
 7         int n;
 8         int duishu;
 9         int temp;
10         int count;
11         int flag;
12         
13         T=scanner.nextInt();
14         while(T!=0){
15             T--;
16             
17             n=scanner.nextInt();
18             count=0;
19             flag=0;
20             while(true){
21                 duishu=(int)(Math.log(n)/Math.log(2));
22                 temp=(int)Math.pow(2,duishu);
23                 
24                 if(flag==0){
25                     count+=duishu;
26                     flag=1;
27                 }
28                 else
29                     count++;
30                 
31                 if(temp==n)
32                     break;
33                 
34                 n-=temp;
35             }
36             System.out.println(count);
37             
38         }    
39     }
40 }
41             
42             

 

 
posted @ 2014-12-01 16:16  zqxLonely  阅读(372)  评论(0编辑  收藏  举报