0

I am writing an algorithm that uses successive squaring to solve a^k mod m. Because of the way successive squaring works, the maximum number that the algorithm will ever have to compute is 2147483646^2 (I limited the user input to 214738364). Unfortunately, it still has to compute this. It seems to get the squaring part right, and then turns the overflowing number into a float, but then can't compute the modulus of a float and an integer.

A sample line is:

3422422^2 mod 715924 = 661224^2 mod 715924 = 437217178176 mod 715924 = -354280

How can I fix this, and how does one find one's way around integer overflow in PHP?

9
  • How can you fix what? That floating-point/integral mod isn't available? Commented Jan 7, 2012 at 17:37
  • Well, obviously a modulo isn't going to return a negative number, yet that is what's occurring here. Is there a special PHP function for the modulus of a float and an integer? Commented Jan 7, 2012 at 17:39
  • What's wrong with modulus returning a negative number? I don't think floating-point has anything to do with it; it's just an overflowed integer. Commented Jan 7, 2012 at 17:42
  • Sorry, I meant the modulus of two positive integers won't return a negative number, as in the example I showed. So what's happening here? I thought that as soon as an integer overflowed in PHP, its type was changed to a floating point number. So after 661224^2 overflow, 4372178176 becomes a float, and then it's trying to compute the modulus of a positive float and a positive integer. Commented Jan 7, 2012 at 17:47
  • 1
    I doubt that's easy to reimplement with a productive runtime behaviour (you'd need to work on strings and simulate integer arithmentic). Which is why bcpowmod() exists. Commented Jan 7, 2012 at 17:49

1 Answer 1

1

I would suggest checking out the GMP extension and reading this question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.