Reputation: 21
Hey so I want to write code for finding nearest square number less than or equal to a certain number(x). I've tried the following:
m = 0
base = 0
while m <= x:
if m > x:
break
m = base**2
base += 1
print(m)
This, however, gives the nearest square right after the number x despite putting the break since a m > x has already been assigned to m. how i do stop the loop before m > x?
Upvotes: 1
Views: 617
Reputation: 2569
Most answers are based on calculating one square too many and then using the previous one.
But is there a possibility to know if the next square will be too big, without calculating it?
m = 0
base = -1
while base*2 + m < x:
base += 1
m = base**2
print(m)
Disclaimer: Just a fun answer to think about why this works.
Upvotes: 0
Reputation: 2379
There's an easier way to do this using math
module:
import math
y = math.sqrt(x) #find the square root of x
if y.is_integer() == False: #check y is not a whole number
print(math.pow(int(y),2)) # find the square root of the nearest whole number to y
Upvotes: 0
Reputation: 45816
The if m > x
is redundant. The loop body will only be entered if m <= x
is True, and if that's True, m > x
never will be, so that break
should never run.
To answer your question though, without knowing more about the math, I'd just introduce a second variable prev_m
, then use that:
m = 0
prev_m = m
base = 0
while m <= x:
prev_m = m
m = base**2
base += 1
print(prev_m) # Then use prev_m instead
Upvotes: 3