快速幂

    快速幂用了分治的思想。首先,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 stub
		long 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秒左右

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值