Search code examples
pythonnumbersrangesquare

Find and print the square numbers in a given range python


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?


Solution

  • 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