Home > Mobile >  Avoid Infinity value when using Math.pow and comparision with loops
Avoid Infinity value when using Math.pow and comparision with loops

Time:11-07

When I do Math.pow(3, num)/num, it is giving me the value if Infinity and when I do modulus of that with 2 it is giving me NaN. I understand NaN is due to Infinity. I am using 300530164787 as the num and am expecting to do a modulus on the above formulae.

Any way I can avoid this?

Math.pow(3, num)/num = Infinity (Math.pow(3, num)/num)%2 = NaN

Second which is faster?

  1. Math.pow(3, num) OR
  2. for loop for 3x3x....

CodePudding user response:

There is a mathematical trick we can apply to allow us using a modular exponentation algorithm:

(a/b) % 2 ≡ (a % 2b) / b

In your case, that will be computing 3**num % (2*num) using modular exponentiation, without loosing considerable number precision on large num values (> 10) or overflowing bigint memory for huge num values (> 1e9). Then you just need to divide by num to get your result.

function modularPow(base, exponent, modulus) {
    if (modulus == 1n) return 0n;
    let result = 1n;
    base = base % modulus;
    for (; exponent; exponent >>= 1n) {
        if (exponent & 1n) result = (result * base) % modulus;
        base = (base * base) % modulus;
    }
    return result;
}

const num = 300530164787n;
console.log(Number(modularPow(3n, num, 2n*num)) / Number(num));

CodePudding user response:

I'm not sure about what you want to accomplish with that...

But since mod 2 yields a recursive result for odd or even numbers, returning only 1 or 0, and the function (3^x)/x>1 for any integer x>0, you don't really care about how large is the first fraction, the only thing you care is whether it's even or odd... So why don't you define a large number (less than the necessary to get the Infinity), and mod the num, say

// Do your thing
var numm = num00;
// this should preserve parity,
// you can use any power of 10
(Math.pow(3, numm)/numm)%2
  • Related