Click here to Skip to main content
15,881,866 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I already finish the task, just need an explanation. I'm trying to compute the nearest square of a number less than a limit using python. Let's say if my limit is 40, then the nearest square would be 36 (from 6*6).

What I have tried:

I already found the answer, but need some explanation :

limit = 40
num = 0

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

print(nearest_square)

It works, the output answer is 36. But I'm still a little bit confused about the condition needed. Originally, I put this :
while (num**2) < limit:

But the answer is 49, which means 7*7 and more than the limit. Why does the "+1" needed in the condition ? Is it not like "for" loop ?
Posted
Updated 7-Feb-20 10:36am
v3

1 solution

First a typo: "But the answer is 49, which means 7*7"
Quote:
I'm trying to compute the nearest square of a number less than a limit using python.

If limit is 36, which answer do you expect 25 or 36 ?
Quote:
It works, the output answer is 36. But I'm still a little bit confused about the condition needed.

You loop until condition is wrong, and it turn wrong when num is 1 step too far.
You could have done it that way:
Python
limit = 40
num = 0
while num**2 < limit:
    num += 1
nearest_square = (num-1)**2
print(nearest_square)
 
Share this answer
 
Comments
lock&_lock 7-Feb-20 16:40pm    
Thanks for pointing out my typo and giving explanation. If my limit is 36, I'd expect the result = 36, that I believe I can manage. When it's ONE STEP TOO FAR, now I understand how it works, thank you. I'm gonna remember this.
CPallini 7-Feb-20 17:04pm    
5.
Patrice T 7-Feb-20 17:13pm    
Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900