试题 算法训练 幂方分解

问题描述
  任何一个正整数都可以用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;
}

 

posted @ 2020-04-16 14:52  haust_zbx  阅读(276)  评论(0编辑  收藏  举报