最少乘法次数

时间限制:1000 ms  |  内存限制:65535 KB
难度:3
 
描述

给你一个非零整数,让你求这个数的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

 

 

 

思路:树的应用,划分

 

 

 
#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;

int main(){
    int n;
    cin>>n;
    while (n--)
    {
        int m;
        cin>>m;
        int times = 0;
        while (m!=1)
        {
            if (m % 2 ==1)
            {
                times += 2;
            }else
            {
                times++;
            }
            m/=2;
        }
        
        cout<<times<<endl;
    }

    return 0;
}        

 

相关文章:

  • 2022-12-23
  • 2021-05-03
  • 2021-06-27
  • 2022-12-23
  • 2022-12-23
  • 2021-06-12
  • 2022-01-05
  • 2022-12-23
猜你喜欢
  • 2021-10-10
  • 2021-09-17
  • 2022-12-23
  • 2021-11-09
  • 2021-07-21
相关资源
相似解决方案