快速幂

来源:互联网 发布:移动网络优化的方法 编辑:程序博客网 时间:2024/04/30 01:26

    快速幂用了分治的思想。首先,a^b = a^c * a^d(c + d = b),然后可以分成大致相等的两部分进行乘方,然后再合并。时间复杂度为O(n/2)

 

   因为本人比较懒(不想做高精度乘法)就用java实现了。
import java.io.*;import java.util.*;import java.math.*;public class fast {/** * @param args */public static BigDecimal power(long bottom,long times){if (bottom == 0)return (new BigDecimal(0));BigDecimal result = new BigDecimal(1);if (times == 0 || times == 1 || times == 2){switch((int)times){case 0:{result = new BigDecimal(1);}case 1:{result = new BigDecimal(bottom);}case 2:{result = result.multiply(new BigDecimal(bottom));result = result.multiply(new BigDecimal(bottom));}}}else{result = power(bottom,times / 2);result = result.multiply(power(bottom, times - times / 2));//分治}return result;}/*快速版*/public static BigDecimal normalPower(long bottom,long times){BigDecimal result = new BigDecimal(1);for (long i = 1;i <= times;++i){result = result.multiply(new BigDecimal(bottom));}return result;}/*标准版*/public static void main(String[] args) {// TODO Auto-generated method stublong bottom = 0;long times =100000000;Date begin = new Date();power(bottom,times);Date end = new Date();System.out.println((end.getTime() - begin.getTime()) / 1000);Date begin2 = new Date();normalPower(bottom,times);Date end2 = new Date();if (power(bottom,times).equals(normalPower(bottom,times))){    System.out.println("Right");}System.out.println((end2.getTime() - begin2.getTime())/1000);}}

快速版比普通版快一倍。实际上还可以分治成更多的份(如1000份,比普通版本快20倍)

比如说我分成1000分时,当bottom=1,times = 1000000000时,普通方法要近7秒,而快速版只有0.35秒左右