-5

I was stuck in a question which asked to find (2^n)%p where n is a very large number of the order 10^36 and p is a prime.How to do this quickly???Here ^ means power I came across this algorithm but it gives stack overflow as 10^36 is very large

double power(double a,double b,int mod)
{
if (b==0)
return 1;
else if(b%2==0)
return square(power(a,b/2,mod))%mod;
else return power(a,b-1,mod)%mod;
}

Is their any other way or an improvement on this??

Gumbo
  • 643,351
  • 109
  • 780
  • 844
codeKNIGHT
  • 63
  • 1
  • 8

2 Answers2

1

You can use divide and conquer approach.

Here is the basic idea:

2^8 = (2^4)^2 2^4 = (2^2)^2

Therefore, you would need to calculate 2^2 once and square it to get 2^4. Then Square that result to get 2^8 and so on.

The demonstrated case, works perfectly if n is a power of 2. However, It's possible to break any powers like this into 2 or 3 sub-problem.

For example, if n = 20, it would break to (2^10)^2. if n = 21, it would break to (2^10)^2 * 2.

Therefore, depending on odd and even value for the power, you could dissolve it into component.

Hope the illustration was clear.

Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
  • Also known as exponentiation by repeated squaring if OP needs keywords to google. – Daniel Fischer Jan 05 '12 at 11:10
  • Yes I know that but 10^36 is very high and gives stack overflow in my recursive procedure...Is their any improvement on that or any quicker way?? – codeKNIGHT Jan 06 '12 at 16:31
  • @user1020998: You could try to implement the same in non-recursive way. However, since it's twos power and p is prime, there maybe some kind of mathematical trick, but I am not aware any as of now. – Shamim Hafiz - MSFT Jan 06 '12 at 18:09
-1

In this case Python can help you. In python you need not to take care about the range of the data type, you just give the value of data python will adjust the data type of the variables automatically.