Fermat’s Last Theorem using Python
Posted by Samath
Last Updated: March 02, 2015

Fermat’s Last Theorem says that there are no integers a, b and c such that

an+bn=cn      for any values of n greater than 2.

Write a function check_fermat that takes four parameters a,b,c & n and checks if Fermat’s theorem holds. If n is greater than 2 and it turns out that an+bn=cn then print “I made a discovery - Fermat was wrong” and return False, otherwise return True. For n equal to 1 or 2 return True if the Fermat’s theorem holds and False otherwise. For values of n less than equal to 0 print an error message.

e.g.
check_fermat(3,4,8,1) -> False
check_fermat(3,4,5,2) -> True
check_fermat(3,4,7,2) -> False
check_fermat(3,4,5,3) -> True

Code:

import math

def check_fermat(a,b,c,n):
    num1 = math.pow(a,n)
    num2 = math.pow(b,n)
    num3 = math.pow(c,n)
    sumnum = num1 + num2
    
    if(n > 2):
        if(sumnum == num3):
            print("I made a discovery - Fermat was wrong")
            return False
        else:
            return True
    elif(n < 0):
        print("Error!!! Number must be greater than 0")

 

Related Content