Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pow and mod function optimization

Tags:

javascript

I need to create an optimized function to count Math.pow(a,b) % c; in Javascript;
There's no problems while counting small numbers like:
Math.pow(2345,123) % 1234567;
But if you try to count:
Math.pow(2345678910, 123456789) % 1234567;
you'll get incorrect result because of Math.pow() function result that cannot count up "big" numbers;
My solution was:

function powMod(base, pow, mod){
    var i, result = 1;
    for ( i = 0; i < pow; i++){
        result *= base;
        result %= mod;
    }
return result;

Though it needs a lot of time to be counted;
Is it possible to optimized it somehow or find more rational way to count up Math.pow(a, b) % c; for "big" numbers? (I wrote "big" because they are not really bigIntegers);

like image 629
ted Avatar asked May 13 '11 08:05

ted


People also ask

What is pow () function?

pow() The Math.pow() method returns the value of a base raised to a power. That is. π™ΌπšŠπšπš‘.πš™πš˜πš  ( 𝚑 , 𝚒 ) = x y.

What is the time complexity of POW function in C++?

Complexity of inbuilt pow function. for c or c++ O(log(N)) but as we know c++ does not support any inbuilt datatype which can handle such large values even 2^100 … It is usually avoided for large values . for python O(log(N)) even there are other option available in that language .

How do you calculate POW?

The most basic way to calculate the nth power of a number is to multiply that number exactly n-times. In this case, we could just find the inverse of its positive power i.e. pow(2,-3) = 1/(2^3).


2 Answers

Based on SICP.

function expmod( base, exp, mod ){
  if (exp == 0) return 1;
  if (exp % 2 == 0){
    return Math.pow( expmod( base, (exp / 2), mod), 2) % mod;
  }
  else {
    return (base * expmod( base, (exp - 1), mod)) % mod;
  }
}

This one should be quicker than first powering and then taking remainder, as it takes remainder every time you multiply, thus making actual numbers stay relatively small.

like image 76
Draco Ater Avatar answered Sep 20 '22 22:09

Draco Ater


Your method is good so far, but you will want to do http://en.wikipedia.org/wiki/Exponentiation_by_squaring also known as http://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method

The idea is that x^45 is the same as (expanded into binary) x^(32+8+4+1), which is the same as x^32 * x^8 * x^4 * x^1

And you first calculate x^1, then x^2 == (x^1)^2, then x^4 == (x^2)^2, then x^8 == (x^4)^2, then...

like image 39
ninjagecko Avatar answered Sep 18 '22 22:09

ninjagecko