Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading