372. Super Pow

Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.

Example1:

a = 2
b = [3]

Result: 8

Example2:

a = 2
b = [1,0]

Result: 1024

Credits:

Special thanks to @Stomach_ache for adding this problem and creating all test cases.


快速幂取模




求a^b % c ,得到以下函数 ,复杂度为Ologb

public int PowerMod(int a, int b, int c)
	{
		int ans = 1;
		a = a % c;
		while (b > 0)
		{
			if (b % 2 == 1)
				ans = (ans * a) % c;
			b = b / 2;
			a = (a * a) % c;
		}
		return ans;
	}


这里的b表示为数组的形式,每次b/2比较麻烦,主要慢在这里,复杂度 O(length_of(b)*log b)

 public int superPow(int a, int[] b)
	{
		return PowerMod1(a, b, 1337);
	}
	
	public int PowerMod1(int a, int[] b, int c)
	{
		int ans = 1;
		a = a % c;
		int bheightestbit=0;
		int len=b.length;
		
		while (b[bheightestbit] > 0)
		{
			if (b[len-1] % 2 == 1)
				ans = (ans * a) % c;
			
			boolean setheightest=false;
			for(int i=bheightestbit;i<len;i++)
			{
				int bitnum=b[i];
				int mod=bitnum%2;
				b[i]=bitnum/2;
				if(mod==1&&i<len-1)
					b[i+1]+=10;
				if(!setheightest&&b[i]>0)
				{
					setheightest=true;
					bheightestbit=i;
				}
			}
				
			a = (a * a) % c;
		}
		return ans;
	}
	



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值