zl程序教程

您现在的位置是:首页 >  其他

当前栏目

试题 算法训练 幂方分解

2023-09-14 09:14:25 时间

试题 算法训练 幂方分解

资源限制
内存限制:256.0MB C/C++时间限制:1.0s Java时间限制:3.0s Python时间限制:5.0s
问题描述
  任何一个正整数都可以用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表示(在表示中不能有空格)

提交代码

#include <iostream>
#include <cstring>
#include <math.h>
using namespace std;

int  j,k,t;
void fun(int n)
{
	int i=0,ans=1,k=n;
	while(n)
	{
		n/=2;
		ans*=2;
		i++;
	}
	t=i-1;
	ans/=2;
	if(t>2)
	{
		cout<<2<<"(";
		fun(t);
		cout<<")";
	}
	else if(t==2||t==0)
	{
		cout<<2<<"("<<t<<")";
	}
	else if(t==1)
	{
		cout<<2;
	}
	n=k-ans;
//	cout<<ans<<n;
	if(n>0)
	{
		cout<<"+";
		fun(n);
	}

}

int main()
{
	int n;
	cin>>n;
	fun(n);
    return 0;
}