天天看点

快速幂和快速乘

快速幂运算

import java.util.*;

public class Main {
	public static void main(String[] args) {
		// 用快速幂运算计算2的30次方花费的时间
		long time = System.currentTimeMillis();
		System.out.println(fast_pow(2, 30));
		System.out.println(System.currentTimeMillis() - time);
		System.out.println();

		// 用math的幂运算2的30次方花费的时间
		time = System.currentTimeMillis();
		System.out.println(Math.pow(2, 30));
		System.out.println(System.currentTimeMillis() - time);
	}

	// 计算x的n次方的快速幂运算
	// 将n转化为2进制表示,若末位为1,则将res乘以相应的值
	// 若n为22,则二进制为10110,需要计算出x的2,4,16次方,当n右移到相应位置时,直接将res乘以相应的x即可。
	static long fast_pow(int x, int n) {
		long res = 1;
		while (n > 0) {
			// n为奇数
			if ((n & 1) == 1) {
				res *= x;
			}
			// n右移一位
			n >>= 1;
			// x变为x的平方
			x *= x;
		}
		return res;
	}
}

           

快速乘运算

import java.util.*;

public class Main {
	public static void main(String[] args) {
		System.out.println(fast_mul(2, 3));
	}

	// 比如5*3相当于5*二进制的11,相当于5*二进制的10+5*二进制的1,如下代码即利用了该思路
	static long fast_mul(long a, long b) {
		long res = 0;
		while (b != 0) {
			if ((b & 1) == 1) {
				res += a;
			}
			a *= 2;
			b >>= 1;
		}
		return res;
	}
}