Reputation: 73
I have been asked to write a program that prints all square numbers less than the one input. However, there is one very slight problem in this code that I can't seem to pinpoint:
from math import sqrt
n=int(input())
counter = 0
while counter * counter < n:
counter = counter + 1
print(counter * counter)
See, the problem is, it prints all the correct squares, but also the square that was input. Could someone please give me an idea of how to solve this? Thanks for the help.
Upvotes: 0
Views: 87
Reputation: 1121484
Simply move the increment down one line and start counting at 1:
n=int(input())
counter = 1
while counter * counter < n:
print(counter * counter)
counter += 1
In your code counter
is incremented after testing it against n
but before printing the square. So even if counter * counter
is smaller than n
, (counter + 1) * (counter + 1)
does not have to be.
By moving the increment down a line, you are properly printing counter * counter
, the value you just tested against n
.
Upvotes: 3