Search code examples
pythonpython-3.xnumber-theory

Question about modulus of large numbers in Python


I used Fermat's Little Theorem and found that 40^65 % 7 = 3. But when I use the following code in Python the answer it prints is 2.0:

print((math.pow(40,65) % 7))

Why does Python give the result incorrectly as 2.0?

Thank you


Solution

  • math.pow(40,65) returns a float, which is an approximation.

    Try (40**65) % 7 instead.

    Once you're happy that the maths works, you can use the built-in function pow to calculate powers and mods in combination:

    pow(40, 65, 7)