zoukankan      html  css  js  c++  java
  • 试题 算法训练 幂方分解

    问题描述
      任何一个正整数都可以用2的幂次方表示。例如:
      137=27+23+20
      同时约定方次用括号来表示,即ab 可表示为a(b)。
      由此可知,137可表示为:
      2(7)+2(3)+2(0)
      进一步:7= 22+2+20 (21用2表示)
      3=2+20
      所以最后137可表示为:
      2(2(2)+2+2(0))+2(2+2(0))+2(0)
      又如:
      1315=210 +28 +25 +2+1
      所以1315最后可表示为:
      2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
    输入格式
      输入包含一个正整数N(N<=20000),为要求分解的整数。
    输出格式
      程序输出包含一行字符串,为符合约定的n的0,2表示(在表示中不能有空格)
     
    思路:    做此题让我个数学渣不得不回忆一下中学知识 
           关于log(N) 默认的是以e为底对(N)求的对数
         c++里exp(n)函数值为e的n次方e^n,log函数包括两种函数,log()函数以e为底,log10()函数以10为底
         引入cmath库文件后 log2(N)即以2为底对N求的对数   例如:log2(1024) = log2(2^10)= 10
       

         代码就要一边模拟递归来思考

    #include <iostream>
    #include <algorithm>
    #include <cstring>
    #include <cstdio>
    #include <cmath>
    
    #define ci cin.tie(0)
    #define ios ios::sync_with_stdio(false)
    #define fi first
    #define se second
    
    using namespace std;
    
    typedef long long LL;
    typedef pair<int, int> PII;
    
    int n;
    
    void divide(int x)
    {
        bool flag = false;
        while (x)
        {
            int t = int(log2(x));
            if (flag) cout << "+";
            if (t == 1) cout << "2";
            else if (t == 0) cout << "2(0)";
            else
            {
                cout << "2(";
                divide(t);
                cout << ")";
            }
            x -= pow(2, t);
            flag = true;
        }
    }
    
    int main()
    {
        ci;ios;
        cin >> n;
        divide(n); 
        return 0;
    }
  • 相关阅读:
    nodejs安装autoprefixer
    nodejs安装Yui Compressor
    js捕捉回车事件
    支付宝服务窗前台页面规范
    html5 input type number 去掉加减号
    [USACO10HOL]赶小猪题解
    [USACO09FEB]改造路题解
    [HNOI2013]游走题解
    洛谷P1649 [USACO07OCT]障碍路线Obstacle Course BFS 最小转弯
    洛谷P1467 循环数 Runaround Numbers
  • 原文地址:https://www.cnblogs.com/zbx2000/p/12712892.html
Copyright © 2011-2022 走看看