JAVA算法趣味题目求解

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值