错误相减
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
*/
}
}