码迷,mamicode.com
首页 > 其他好文 > 详细

Integer Break

时间:2016-05-01 09:52:50      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

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.

 1 public class Solution { 
 2     int integerBreak(int n) {
 3         int result=0;
 4         double e=2.718281828459;
 5         int breakNumber=(int) (n/e);
 6         if (breakNumber<2) {
 7             return n/2*(n-n/2);
 8         }
 9         for (int i = breakNumber-1; i <=breakNumber+1; i++) {
10             int breakValue=n/i;
11             int valueOverNumber=n%i;
12             int resultTemp=0;
13             if (valueOverNumber!=0) {
14                 resultTemp=(int) ( Math.pow(breakValue, i-valueOverNumber)
15                         * Math.pow(breakValue+1, valueOverNumber));
16             }else {
17                 resultTemp=(int) ( Math.pow(breakValue, i));
18             }
19 
20             if (resultTemp>result) {
21                 result=resultTemp;
22             }
23         }
24         return result;
25         
26     }
27 }

由数学计算可以证明已知y=x1+x2+...+xn, z=x1*x2*...xn最大时,应满足x1=x2=...xn=y/n,且分割数n=y/e

Integer Break

标签:

原文地址:http://www.cnblogs.com/zoghin/p/5450055.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!