3

Let me be brief. I'm trying to calculate

alert((Math.pow(7,35))%71)

but it gives me 61, when the result must be 70. What's wrong?

3 Answers3

2

The number you're using is too big for javascript. The max size of an int is 2^53 -- which is less than 7^35.

istrupin
  • 1,423
  • 16
  • 32
2

As others mentioned before with regards to using Math.pow(7,35), this resulting number is way too big for Javascript to handle.

To resolve your problem you need to use an external javascript library. (Or write your own ;) )

Here are some examples of Javascript libraries that handle big numbers.

  1. BigNum
  2. Bignumber

I hope it helps.

istrupin
  • 1,423
  • 16
  • 32
Adrian Grzywaczewski
  • 868
  • 1
  • 12
  • 25
0

The only value which requires more precision is an intermediate result. So the problem can also be avoided without the need for higher precision variables when you have an algorithm that doesn't need the problematic intermediate result.
The following formula can be useful for that: (a.b) % c = (a % c)(b % c) % c
This means Math.pow(7,35)%71 = ((Math.pow(7,17)%71) * (Math.pow(7,18)%71)) % 71.
Now the intermediate results are smaller, but might still be too big. So we need to split up further and to apply the modula operator on smaller intermediate results.
So you can do something like this: Math.pow((Math.pow(7,7)%71),5)%71

But you probably need to do this for integer numbers wich are variable (otherwise, you could have avoided the problem by hardcoding the result). So, you need to have an idea about the range of values you can expect and to define an algoritm that splits up the power calculation into pieces that will always have results that are small enough when the input is within the expected range.

And whatever you choose for a calculation like this, calculation with higher precision variables (using a specialized library) or a specilized algoritm, you should always assert the input to make sure your calculation returns a value only when you are sure it can deliver a correct value. Otherwise your implementation becomes unreliable for anyone who isn't aware of the range in which it is valid. Otherwise return an exception with a message that tells clearly which input or combination of inputs is the problem and why.