给定一个正整数N,将其表示为数字1,3,7,15相加的形式输出。请编码找出使上述数字出现的总次数最少(每个数字可以重复使用)的组合。
- 输入说明:一个正整数N(N<=10000)。
- 输出说明:正整数N由1,3,7,15组成的加法表达式,左侧是N,之后是’=‘号,’='右侧是数字加和的形式,要求非递增排列。
- 举例:
输入:17
输出:17=15+1+1
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
int a = N / 15;
int b = (N - a * 15) / 7;
int c = (N - a * 15 - b * 7) / 3;
int d = N - a * 15 - b * 7 - c * 3;
string str;
while (a > 0)
{
str += "15+";
a -= 1;
}
while (b > 0)
{
str += "7+";
b -= 1;
}
while (c > 0)
{
str += "3+";
c -= 1;
}
while (d > 0)
{
str += "1+";
d -= 1;
}
str.erase(str.length() - 1);
cout << N << "=" << str;
return 0;
}
演示截图:
注: