2023.06.20 homework

错误相减 

1 + 2 + 4 + 8 + 16 + 32 + 64 + ..... + K = ???

package homework;

/**
 * 1 + 2 + 4 + 8 + 16 + 32 + 64 + ..... + K = ???
 * 
 *      x = 1 + 2 + 4 + 8 + 16 + 32 + 64 + ..... + K
 * y = 2x =     2 + 4 + 8 + 16 + 32 + 64 + ..... + K + 2K
 * 
 * x = y - x = 2x - x = 2K - 1
 * 
 *   2023.06.20 homework
 *   
 * 错位相减
 *
 * @author ZengWenFeng
 * @email 117791303@qq.com
 * @mobile 13805029595
 * @date 2023.06.20
 */
public class Math_2023_06_20
{
	public static void test1()
	{
		long start = System.nanoTime();
		
		int base = 2;
		int sum = 0;
		int min = 0;
		int max = 100;
		for (int i = min; i <= max; i++)
		{
			sum += Math.pow(base, i);
		}
		
		System.out.println(sum);//2147483647
		
		System.out.println("time : " + (System.nanoTime() - start));//210862
	}
	
	public static void test2()
	{
		long start = System.nanoTime();
		
		int base = 2;
		int sum = 0;
		int min = 0;
		int max = 100;
		
		sum = (int) (Math.pow(base, max + 1) - Math.pow(base, min) + 0);
		
		System.out.println(sum);//2147483647
		
		System.out.println("time : " + (System.nanoTime() - start));//19127
	}

	public static void main(String[] args)
	{
		test1();
		test2();
		/**
		2147483647
		time : 210862
		2147483647
		time : 19127
		 */
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值