124k views
0 votes
Assume there are two variables, k and m, each already associated with a positive integer value and further assume that k's value is smaller than m's. Write the code necessary to compute the number of perfect squares between k and m. (A perfect square is an integer like 9, 16, 25, 36 that is equal to the square of another integer (in this case 3*3, 4*4, 5*5, 6*6 respectively).) Associate the number you compute with the variable q. For example, if k and m had the values 10 and 40 respectively, you would assign 3 to q because between 10 and 40 there are these perfect squares: 16, 25, and 36,.

PYTHON CODING

1 Answer

3 votes

Answer:

import math

def isPerfectSquare(n):

s = int(math.sqrt(n))

return n == s*s

def countPerfectSquares(k,m):

q = 0

for i in range(k,m):

if isPerfectSquare(i):

q=q+1

return q

print(countPerfectSquares(10,40))

Step-by-step explanation:

Note that this is including the k, but excluding m. If you want to include m, write m+1 in the range expression.

User Schmidko
by
6.2k points