从1加到100(考虑减少循环次数)使用数学公式
首先要知道从1加到100的数式; n*(n-1)/2+n; 大家都知道从1加到100等于5050; 不妨用这个公式套一下,看看等不等于5050;
n就是从1加到第几的数字; 100*(100-1)=9900; 9900/2=4950; 4950+100=5050; 看来这个公式是行的通的;所以当你不会用for循环来写的时候,就可以用这种公式的写法了;
/**
*
* 文 件 名 :
* 包: sunTest.java
* 工程:
* 创 建 人: shmily
* 日 期: 2013-2-27上午9:02:49
* 描 述: 累加运算,减少循环次数的一种策略
* http://www.fsti.com
* CopyRright (c) 2012-2013
*/
public class Test {
/**
* shmily
* @param args
* 20132013-2-27上午8:54:36
* void
*/
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.sum(100));
}
/**
*
* shmily
* 默认从1开始到max的总和
* @param max
* @return
* 20132013-2-27上午9:01:59
* int
*/
public int sum(int max){
return max*(max-1)/2+max;
}
}