JAVA算法趣味题目求解
题目一
写一个算法,求下面序列之和: − 1 , 1 , − 1 , 1 , . . . ( − 1 ) n -1,1,-1,1,...(-1)^n −1,1,−1,1,...(−1)n
当看到这个题目时,你会怎么想?
这个题目看起来非常简单,使用for循环,或者while循环等,累加求和呀!
于是就有了第一个算法(JAVA语言实现):
public static int sumSolution_1(int N) {
int result = 0;
for (int i = 1; i <= N; i++) {
result = result + (int) Math.pow(-1, i);
}
return result;
}
但是如果我们找到数字求和之间的规律,将奇数位和偶数位的数先进行累加求和,这会是什么情况呢?
奇数位+偶数位 = 0
-1 | 1 | -1 | 1 |
---|---|---|---|
奇数位 | 偶数位 | 奇数位 | 偶数位 |
这时就可以采用下面的算法:
public static int sumSolution_2(int N) {
int result = 0;
if (N % 2 == 0) {
result = 0;
} else {
result = -1;
}
return result;
}
当给N赋予不同的值,N=4,N=5,…N=10时,可以验证,以上两个算法都可以得到正确并且相同的结果。
但是当 N=10000000,即一千万时;N为1亿时,消耗的计算时间有差别吗?
下面的测试代码运行结果说明了问题:
package com.bean.algorithm.beginner;
public class BeginerSum {
public static int sumSolution_1(int N) {
int result = 0;
for (int i = 1; i <= N; i++) {
result = result + (int) Math.pow(-1, i);
}
return result;
}
public static int sumSolution_2(int N) {
int result = 0;
if (N % 2 == 0) {
result = 0;
} else {
result = -1;
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
//n的取值为一千万
int n = 10000000;
long starttime = System.currentTime