Find and print the square numbers in a given range python

Question:

Find and print the square numbers in a given range python
Here’s my approach

 a, b = int(input()), int(input())
from math import sqrt
for i in range(a, b+1):
    if i%10 != 1 and i%10 != 4 and i%10 !=9 and i%10 !=6 and i%10 !=5:
        pass
    elif sqrt(i) - int(sqrt(i)) == 0:
        print(i, end = " ")

The thing is can this be ultilized so that it run faster?

Asked By: Codeer

||

Answers:

The code above is not producing any result.

Try this –

from time import perf_counter
start = perf_counter()
a, b = int(input()), int(input())
from math import sqrt
for i in range(a, b+1):
    #print(i)
    if i:
        i_sqrt = int(sqrt(i))
        if i_sqrt*i_sqrt==i:
            print(i)

stop = perf_counter()
 
print(stop - start)
Answered By: atg

Although the code you provided skips some of the numbers that cannot be square numbers, it misses some due to not checking for the last digit being 0. A faster approach would be to not check if the current number is a square number but iterate between the square roots of the inputs and print their squares.

from math import sqrt,ceil,floor
a=ceil(sqrt(int(input()))) # We round our first number's square root up because the input to the range function needs to be an integer and we want out first perfect number to be bigger or equal to out first input
b=floor(sqrt(int(input())))
for i in range(a, b+1): # Additional one is for including the second input 
   print(i**2, end = " ") # As we are iterating over integers between the square roots of the inputs, the results will always be integers
Answered By: arfelious
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.