Home > Back-end >  Finding nearest square in python using for loop
Finding nearest square in python using for loop

Time:05-02

I wrote a program to find the nearest square in python using while loop, which goes like the below:

num = 0
while (num 1)**2 < limit:
    num  = 1
nearest_square = num**2
print(nearest_square)

This made me wonder, if we can find the same using a for loop. I am unable to understand how can we set the range of the same.

Can anyone please guide?

Thanks in advance.

CodePudding user response:

This is probably the best way to find the nearest square.

int(limit ** (0.5)) ** 2

If limit = 200 then the output is 196.

But if you want to do the exact same thing you did above using for loop use this,

for num in range(limit   1):
  if (num   1) ** 2 >= limit:
    break

CodePudding user response:

IIUC:

for num in range(round(limit**0.5) 1):
    if (num 1)**2 >= limit:
        break
nearest_square = num**2
  • Related