题目描述:
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
Note: You may assume that n is not less than 2 and not larger than 58.
给定一个数字,将其拆分为a1+a2+...an的和,使得a1*a2...an最大。
一道数学题目。本题主要是找规律。
实现代码以及分析过程:
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
Note: You may assume that n is not less than 2 and not larger than 58.
给定一个数字,将其拆分为a1+a2+...an的和,使得a1*a2...an最大。
一道数学题目。本题主要是找规律。
实现代码以及分析过程:
public class Solution {
public int IntegerBreak(int n) {
if(n < 2){
throw new ArgumentException("n should be more than 2");
}
if(n == 2){return 1;}
if(n==3){return 2;}
if(n ==4){return 4;}
int x = 0;
int k = 0;
if(n%3 == 0){
//6 3^1 * 3
//9 3^2 * 3
//12 3^3 * 3
//15 3^4 * 3
//18 3^5 * 3
// so :
// y = Math.Pow(3,x) * k;
x = (int)(n/3) - 1;
k = 3;
}
else if(n %3 == 1){
//7 3^1 * 2 * 2
//10 3^2 * 2 * 2
//13 3^3 * 2 * 2
//...
// so
// y = Math.Pow(3,x) * k;
x = (int)(n-1)/3 - 1;
k = 4;
}
else {
//5 3^1 * 2
//8 3^2 * 2
//11 3^3 * 2
// ...
// so
// y = Math.Pow(3,x) * k;
x = (int)(n-2)/3;
k = 2;
}
return (int)Math.Pow(3,x) * k;
}
}