Exercise 68

Write a Python algorithm which determines for a given integer, the list of perfect squares between 1 and n. Example if n = 100 the algorithm returns the list

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Solution

# function which tests whether a number is perfect square or not
def perfectSquare(n):
# initialization counter
counter = 0

for i in range (1, n + 1):
if i * i == n:
counter = counter + 1
if counter > 0:
return True
else:
return False

# function which determines the list of perfect squares
def listPerfectSquare(n):
# initialization of the list of perfect squares
lperfect = []
for i in range (1, n + 1):
if perfectSquare(i):
lperfect.append (i)
return lperfect

#Example
n = 100
print (listPerfectSquare (n))
# displays: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Younes Derfoufi
my-courses.net

Leave a Reply