找到并打印给定范围内的平方数Python。

huangapple go评论60阅读模式
英文:

Find and print the square numbers in a given range python

问题

找出并打印给定范围内的平方数 Python
这是我的方法

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=" ")

问题是,是否可以优化以加快运行速度?

英文:

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?

答案1

得分: 2

尽管您提供的代码跳过了一些不能是平方数的数字,但它会因为没有检查最后一位是否为0而错过一些。更快的方法是不检查当前数字是否为平方数,而是在输入的平方根之间进行迭代并打印它们的平方。

from math import sqrt, ceil, floor
a = ceil(sqrt(int(input()))) # 我们将第一个数字的平方根四舍五入,因为范围函数的输入需要是整数,我们希望第一个完全平方数大于或等于第一个输入
b = floor(sqrt(int(input())))
for i in range(a, b+1): # 额外加一是为了包括第二个输入
   print(i**2, end=" ") # 由于我们在输入的平方根之间进行整数迭代,结果将始终是整数
英文:

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

答案2

得分: 1

以上的代码没有产生任何结果。

尝试这个 -

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)
英文:

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)

huangapple
  • 本文由 发表于 2023年3月4日 01:24:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630133.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定