18713 整数的分解
时间限制:1000MS 代码长度限制:10KB
提交次数:0 通过次数:0
题型: 编程题 语言: G++;GCC
Description
输出一个正整数n的分解形式。例如,当n=4时,输出:
4=4
4=3+1
4=2+2
4=2+1+1
4=1+1+1+1
共计 5 种形式。
当n=7时,共有15种形式。
当n=10时,共有42种形式。
输入格式
一个整数n(1<=n<=10)。
输出格式
n的全部分解形式,注意分解式中数字值大的排在前面,如第一个数字值相同,那么比较第二个数字。
输入样例
4
输出样例
4=4
4=3+1
4=2+2
4=2+1+1
4=1+1+1+1
#include <iostream>
using namespace std;
int n;
int ans[15];
void func(int rest,int depth)
{
if(rest==0)
{
cout<<n<<"="<<ans[0];
for(int i=1;i<depth;i++)
{
cout<<"+"<<ans[i];
}
cout<<endl;
return;
}
for(int i=rest;i>=1;i--)//注意这里的初始值,应该是rest而不是n
{
if(depth==0||i<=ans[depth-1])//确保后续的分解因子小于等于前面的
{
ans[depth]=i;
func(rest-i,depth+1);
}
}
}
int main()
{
cin>>n;
func(n,0);
return 0;
}