Exercise 62 || Solution

Create a  Python algorithm that tests whether a given integer is sum of two perfect squares. Example the integer n = 13 is sum of two perfects squares 13 = 2 ^ 2 + 3 ^ 2.

Solution


n = int(input("Enter value of integer n : "))
# initialize solutions
a = 0
b = 0
# initialize counter to test the existence of possible solutions
counter = 0

for i in range(1, n+1):
for j in range(1,n+1):
if i**2 + j**2 == n:
a = i
b = j
counter = counter + 1
break
if ( counter > 0):
print("The integer " , n , " is sum of two perfects squares :"
, n , " = ", a, "^2" ," + " , b ,"^2")
else:
print("The integer " , n , " is not sum of two perfects squares !")

# Testing algorithm for n = 13
# The output is : The integer 13 is sum of two perfects squares : 13 = 3 ^2 + 2 ^2


Younes Derfoufi
my-courses.net

Leave a Reply