Skip to content Skip to sidebar Skip to footer

Nearest Square Function With Python

I have this sample quiz question but not to sure how to approach it with while loops. Implement the nearest_square function. The function takes an integer argument limit, and retur

Solution 1:

Try using the following method to return the nearest square given the limit parameter:

def nearest_square(limit):
    answer = 0
    while (answer+1)**2 < limit:
        answer += 1
    return answer**2

Solution 2:

this is how i did it with while loop:

defnearest_square(value):
    i = 2while i < value:
        square = i*i
        if square == value:
            return square
        i+=1
        value-=1print (nearest_square(40))

Solution 3:

Normally, it's more efficient to approach this kind of questions mathematically (maybe not for low inputs but certainly yes for pretty big numbers). That said, we have a good tool at hand: the square root.

If computing the square root of any number, n, yields a double value whose decimal part is fully composed by zeroes then your number is a perfect square (square of an integer).

Interestingly (and this is more related to your question), if you choose another number (that is not a perfect square) and apply a rounding operation (floor or ceil) you'll get the closest square (lower or bigger).

An example:

n = 24
sqrt = math.sqrt(n) # sqrt(24) = 4.898979485566356...
closest = [math.floor(sqrt)**2, math.ceil(sqrt)**2] # closest = [16, 25]

Solution 4:

def nearest_square(value):

  i =1result=1
  while (result<value):

   if (result==value):
      returnresult
   i+=1result= i*i

  return (i-1)*(i-1)

print (nearest_square(82))

Solution 5:

Here is my code:

`

def nearest_square(limit):
    whilelimit > 3:
        i = 2
        while i <= limit//2:
            square = i*i
            if square == limit:
                return square
            else:
                i += 1
        limit -= 1
    return 1

`

Post a Comment for "Nearest Square Function With Python"