习题5.7 如何分解能使这些数的乘积最大
有一个整数N,N可以分解成若干个整数之和,问如何分解能使这些数的乘积最大。请编程,由键盘输入一个整数N(N<100),将N分解成若干个整数,输出这些数的乘积M,且要保证M是最大的。
//************************************************
//* Source Name: ChapterFive_ExerciseSeven.cpp
//* Founction : How to decompose to maximum the product
//* Author : Skyera
//* Create Time : 2025-7-26
//* Modify :
//* Modify Time:
//************************************************
#include <iostream>
using namespace std;
int main()
{int n;cout << "请输入一个整数N(N<100): ";cin >> n;// 处理特殊情况if(n == 2){cout << "最大乘积是: 2" << endl;return 0;}if(n == 3){cout << "最大乘积是L 3" << endl;return 0;}int quotient = n / 3; // 商int remainer = n % 3; // 余数int maxProduct = 1;// 根据余数情况计算最大乘积if(remainer == 0){// 余数为0,全部分解为3for(int i = 0; i < quotient; i++){maxProduct *= 3;}}else if(remainer == 1){// 余数为1,将一个3和1转为两个2(因为2*2>3*1)for(int i = 0; i < quotient - 1; i++){maxProduct *= 3;}maxProduct *= 4; // 2*2=4}else // remainder == 2{// 余数为2,直接乘以2for(int i = 0; i < quotient; i++){maxProduct *= 3;}maxProduct *= 2;}cout << "最大乘积是: " << maxProduct << endl;return 0;
}