Share your repls and programming experiences

← Back to all posts
6.1. While: List of squares
pole55

"For a given integer N, print all the squares of positive integers where the square is less than or equal to N, in ascending order."

Example input
50

Example output
1 4 9 16 25 36 49

Voters
douglassuarez
aidanburns20
109b30569
ReinisMuiznieks
OliviaMartino21
jfazali01
KhicheenguiElbe
NehalPraveen
tomsfy
CookLea
Comments
hotnewtop
girianshiido

I think it's better to use a while loop here.
For example, if x is one million, the last number of the list will be one million, but you'll compute the square of each number from one to one million (so the last square will be one trillion).

pole55

@girianshiido This code publishes only squares which are less than a given number. We have "if i*2 <= x" here for this. it is equal to your "while ii <= x". just try it // Link to the task: https://repl.it/student/submissions/3764967

girianshiido

@pole55 what I meant is that your script is computing too much stuff for its purpose. That's because range(1, x+1) is way too big, especially if x itself is big. If x=10^10, then you only really need to stop at 10^5, because the square of this number is 10^10.
Here is a modification of your own script:

Try your script with x = 10000000000 and try this new version. You'll see the difference.

pole55

@girianshiido, my code gives the same result
https://storage.googleapis.com/replit/images/1537369635000_7eccae89e39c716a1781be52cfbf5ef0.pn
https://storage.googleapis.com/replit/images/1537369635023_e9ae3400c2da4b4d9d39fc9cfdb47287.pn

pole55

its all because of "if i**2 <= x" that tells to stop at "10^5" (in your words). without this part, it will print "10^10".

girianshiido

@pole55 Did you try your code with 10000000000?
Your code doesn't tell to stop at 10^5. It'll try to compute each square from 1 to x², even if i² is already greater than x. Of course, none of these numbers will be in the list, because they don't verify the condition.

pole55

@girianshiido the result does not depend on the value of the number. they are still identical. p.s.: I use here a million cause the computer hangs trying to work with 10000000000)). in both, my and yours, cases.
https://storage.googleapis.com/replit/images/1537371463115_eca8571f0390d14c2794c0e379821db1.pn
https://storage.googleapis.com/replit/images/1537371463102_945da99be1ffa0165f5437150465a0e5.pn

pole55

@girianshiido oh. now i see what you are talking about! hmm. thanks

girianshiido

@pole55 I know they’re identical. On my 2011 MBA, it takes forever with your code but it works instantly with the sqrt.
By the way, I just realized I forgot to remove the unnecessary condition if i^2 <=x.

JindongSha

THANKS