我想检查数字,基于下界和上界,是否只有3和5的素数除数,数字应该是3的乘数和5的乘数。我目前的解决办法是。我想优化它,因为在我看来,用for循环检查电源不是一个好方法。提前谢谢。
def checkNum(x):
for i in range(1,50):
for j in range(1,50):
return x == (3**i) * (5**j)
def printResult(l, r):
for i in range(l,r):
if checkNum(i):
print(i)根据评论,我认为这是最好的方法:
def checkNum(x):
while x%3==0:
x = x //3
while x%5==0:
x = x//5
return x==1发布于 2020-12-07 04:44:26
我想优化它,因为在我看来,用for循环检查电源不是好方法。
在一系列随机数的范围内,我们通过以下方法来提高它的速度:
def checkNum0(x):
if x % 2 == 0: # eliminate half the numbers in one test!
return False
while x % 15 == 0: # speed up the process
x = x // 15
while x % 5 == 0:
x = x // 5
while x % 3 == 0:
x = x // 3
return x == 1或者我们可以使用嵌套循环并将这两个分区合并为一个:
def checkNum(x):
if x % 2 == 0: # eliminate half the numbers in one test!
return False
for divisor in (15, 5, 3):
while (quotient_remainder := divmod(x, divisor))[1] == 0:
x = quotient_remainder[0]
return x == 1https://stackoverflow.com/questions/65172780
复制相似问题