1+10000 怎樣寫比較快。
剛學會程式的,可能會這樣寫: 耗時(1 ms)
1: public static void main(String[] args) {
2: int sum=0;
3: for (int i=0;i<10000;i++)
4: {
5: sum=sum+(i+1);
6: }
7: System.out.println(sum);
8: }
或是用遞迴: 耗時(1 ms)
1: static int sum = 0;
2: public static void main(String[] args) {
3: culsum(10000);
4: System.out.println(sum);
5: }
6: private static void culsum(int max) {
7: if (max > 0) {
8: sum += max;
9: max -= 1;
10: culsum(max);
11: }
12: }
其實明明有更簡單的方式 -> (上底+下底) * 高 / 2
(1+10000)*10000 /2= 10001*5000=5000500
耗時(0 ms)
1: static int sum = 0;
2: public static void main(String[] args) {
3: int start = 1;
4: int max = 10000;
5: sum = (start + max) * ((max - start) + 1) / 2;
6: System.out.println(sum);
7: }
沒有留言:
張貼留言