Skip to content Skip to sidebar Skip to footer

Javascript Number Too Big For Modulo

Just a simple question. I am trying to calculate something in js: print(pow(49, 37) % 77) this will print 22 instead of what it schould really be (14). I am just not sure if this

Solution 1:

This is a common operation in cryptography What you can do is to compute the power yourself iteratively, and at each iteration you reduce it mod 77. The function powmod below is what you have to do, all the rest is to make the snippet interactive.

functionpowmod(a, b, mod){
  if(b < 1){
    return1;
  }
  const t = powmod(a, b >> 1, mod);
  if(b & 1){
    return (a * t * t) % mod;
  }else{
    return (t * t) % mod;
  }
}

const a = document.getElementById('a');
const b = document.getElementById('b');
const c = document.getElementById('c');
const d = document.getElementById('d');
functionupdate(){
  d.value = powmod(parseInt(a.value), parseInt(b.value), parseInt(c.value))
}

[a,b,c].map(e => e.addEventListener('change', update))
update()
pow(<inputtype="number"min="0"max="999999"step="1"id="a"value="49">, 
<inputtype="number"min="0"max="999999"step="1"id="b"value="37">) % 
<inputtype="number"min="0"max="999999"step="1"id="c"value="77"> = 
<inputtype="number"min="0"max="999999"step="1"id="d"disabled>

Post a Comment for "Javascript Number Too Big For Modulo"