天天看點

正整數幂次方遞歸表示

連結:https://ac.nowcoder.com/acm/contest/1069/L

來源:牛客網

任何一個正整數都可以用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)

/* ***********************************************
Author        :pall_scall
Created Time  :2019年07月29日 星期一 09時58分28秒
File Name     :a.cpp
************************************************ */

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <string>
using namespace std;

typedef long long ll;
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) x&-x
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7;
const double eps = 1e-6;
const double pi = acos(-1.0);
void dfs(int n,int x){ //n目前剩餘  x幂次
	if(n == 1){
		if(x == 0) printf("2(0)");
		else if(x == 1) printf("2");
		else if(x == 2) printf("2(2)");
		else{
			printf("2(");
			dfs(x,0);
			printf(")");
		}
	}else{
		dfs(n/2,x+1);
		if(n%2 == 1){
			if(x == 0) printf("+2(0)");
			else if(x == 1) printf("+2");
			else if(x == 2) printf("+2(2)");
			else{
				printf("+2(");
				dfs(x,0);
				printf(")");
			}
		}
	}

}
int main(){
	//freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	int n;
	cin>>n;
	dfs(n,0);
    return 0;
}
           
dfs

繼續閱讀