Description
对一个自然数N ( 1 <= N <= 50 ) ,N可以分解成若干个数字(数字可以是1,2,3,….,9)之和,问题是如何分解能使这些数字的乘积最大。
Input
输入数据有多组,每组占一行,每行包含一个自然数N(1 <= N <= 50)。输入文件直到EOF为止!
Output
对每组输入,输出有2行。第一行是N分解出的所有数字,以空格分隔,最后一个数字后也有空格;第二行是N分解出的所有数字的个数、乘积。
Sample Input
20 24 28
Sample Output
3 3 3 3 3 3 2 7 1458 3 3 3 3 3 3 3 3 8 6561 3 3 3 3 3 3 3 3 4 9 26244
Hint
由数学知识可知,只有把N分成尽可能多的3,它们的乘积才能最大(当只剩下4时不用再分,因为: 4 > 3*1)
思路: 这个题一共分为 几种情况
1.输入的数字 小于 3
2.输入的数字大于3 : 一是:这个数可以整除3 二是:为 当 n-4 可以 整出 3 和n-4不能 整出 3 .
代码:
#if 0 // m 数值分解
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int ans=0,x=0;
if(n==1)
cout<<"1 "<<endl<<"1 1"<<endl;
else
if(n==2)cout<<"2 "<<endl<<"1 2"<<endl;
else
if(n%3==0)
{
x=n/3;
for(int i=0;i<x;i++)
cout<<"3 ";
cout<<endl<<x<<" "<<(long long int)pow(3,x)<<endl;
}
else
if((n-4)%3==0)
{
x=(n-4)/3;
for(int i=0;i<x;i++)
cout<<"3 ";
cout<<"4 "<<endl;
cout<<x+1<<" "<<(long long int)pow(3,x)*4<<endl;
}
else
{
x=n/3;
ans=n%3;
for(int i=0;i<x;i++)
cout<<"3 ";
cout<<ans;
cout<<endl<<x+1<<" "<<(long long int)pow(3,x)*ans<<endl;
}
}
}
#endif
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int ans=0,x=0;
if(n==1)
cout<<"1 "<<endl<<"1 1"<<endl;
else
if(n==2)cout<<"2 "<<endl<<"1 2"<<endl;
else
if(n%3==0)
{
x=n/3;
for(int i=0;i<x;i++)
cout<<"3 ";
cout<<endl<<x<<" "<<(long long int)pow(3,x)<<endl;
}
else
if((n-4)%3==0)
{
x=(n-4)/3;
for(int i=0;i<x;i++)
cout<<"3 ";
cout<<"4 "<<endl;
cout<<x+1<<" "<<(long long int)pow(3,x)*4<<endl;
}
else
{
x=n/3;
ans=n%3;
for(int i=0;i<x;i++)
cout<<"3 ";
cout<<ans;
cout<<endl<<x+1<<" "<<(long long int)pow(3,x)*ans<<endl;
}
}
}
#endif