题目
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.
简单的观察就能知道拆出足够多的 3 就能使得乘积最大。
int integerBreak(int n)
{
if(n == 2) return 1;
if(n == 3) return 2;
int ret = 1;
while( n>4 )
{
ret *= 3;
n -= 3;
}
return ret * n;
}
实现起来的确很容易,但是问题来了,为什么是3呢?
于是查阅了一些与数学有关的问题:
首先证明拆出的因子大于 4 是不行的。设 x 是一个因子,x>4,那么可以将这个因子再拆成两个因子 x−2 和 2,易证 (x−2)×2>x。所以不能有大于 4 的因子。
4 这个因子也是可有可无的,4=2+2,4=2×2。因此 4 这个因子可以用两个 2 代替。
除非没有别的因子可用,1 也不能选作因子。一个数 x 当它大于 3 时,有 (x−2)×2>(x−1)×1。
这样呢,就只剩下 2 和 3 这两个因子可以选了。下面再证明 3 比 2 好。
其实最佳的是e,但是题目要求的是整数,所以3最佳;