0

I am currently writing a program that requires the calculation of:

(x^2) mod y

Both these numbers are integers. Both can be large numbers, though they never exceed 10^9.

That is still enough to overflow integer for x squared. Speed is crucial for this code so gradual multiplication is not usable.

Thank you.

Simon
  • 43
  • 5
  • Possible duplicate of [Calculate a\*a mod n without overflow](https://stackoverflow.com/questions/10076011/calculate-aa-mod-n-without-overflow) – phuclv May 30 '19 at 15:58

2 Answers2

0

You can take a reference from this post

This should be a relatively easy example. 4^23=2^46. Now, since 2^5=32≡1(mod31),

2^46=(2^5)9×2=32^9×2≡1×2≡2(mod31)

Community
  • 1
  • 1
Vivek Kothari
  • 462
  • 6
  • 20
0

The solution was really simple. I used Long, instead of int and it works.

Simon
  • 43
  • 5