马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
标题
给定一个正整数 n ,将其拆分为 k 个 正整数 的和( k >= 2 ),并使这些整数的乘积最大化。
返回 你可以得到的最大乘积
- 示例 1:
- 输入: n = 2
- 输出: 1
- 表明: 2 = 1 + 1, 1 × 1 = 1
- 示例 2:
- 输入: n = 10
- 输出: 36
- 表明: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
- 提示:2 <= n <= 58
代码
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int main()
- {
- while (1)
- {
- int n;
- scanf("%d",&n);
- if (n<2 || n>58)
- return 0;
- int three_n = n/3;
- int yushu = n%3;
- int end = 1;
- if (yushu == 1)
- {
- three_n--;
- for (int i = 0; i < three_n; i++)
- {
- end = end * 3;
- }
- end = end * 4;
- }
- else if (yushu == 2)
- {
- for (int i = 0; i < three_n; i++)
- {
- end = end * 3;
- }
- end = end * 2;
- }
- printf("end = %d\n",end);
- }
- return 0;
- }
复制代码 剖析
- 什么数相乘最大
- 将一个数拆分为多个3,由于3的乘积最大
- 当余数为1的时间,将一个3拆出来合成为4(1+3),乘积最大
- 当余数为2的时间,直接多个3相乘再乘于2的乘积最大
举例
|