快速幂
来源:互联网 发布:移动网络优化的方法 编辑:程序博客网 时间: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秒左右
- 快速矩阵快速幂
- 快速幂,快速幂取模
- 快速幂 + 快速幂取模
- 快速幂 快速幂取模
- 快速幂&&快速乘法
- 快速幂&快速乘
- 快速幂 快速乘法
- 快速幂 快速幂取模
- 快速幂+快速乘法
- 【快速幂】【快速幂取模】
- 快速乘法-快速幂
- 快速乘/快速幂/矩阵快速幂
- 快速乘 快速幂 矩阵快速幂
- 快速幂,快速幂取模,矩阵快速幂
- 快速幂
- 快速幂
- 快速幂
- 快速幂
- 善用 Eclipse 组合键,提高输入效率
- 第二十天博客
- 基于 TMS320C28x+DSP 的FFT 在CCS4的实现
- 学习笔记——XML Schema自定义数据类型(续)
- 关于CODE::BLOCKs的下载、安装与使用
- 快速幂
- (精)hdoj 2188 (博弈论)
- 百度空间技术博客
- 不要62 //java字符串功能强大呀
- 简单趣味题
- 基于linux-2.6.38.8内核的SDIO/wifi驱动分析
- XAF 如何用其他线程更新对象(转载)
- 今天是2012年3月25日
- JAVA