所以我有涉及Super B primes的这个问题。 Super B prime基本上就是这个。
然后n是Super B prime。 例如。
=======
问题在于我必须在范围(a,b)中打印每个Super B Prime,而我现在已经超过时间限制了很多。我该如何改进呢?
import math
from functools import lru_cache
@lru_cache()
def is_prime(n):
if n<1:
raise ValueError("Must be positive integer")
elif n>1:
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
@lru_cache()
def dec_to_binary(n):
return int(bin(n)[2:])
a,b = map(int,input().split())
for i in range(a, b+1):
l=0
k=0
for m in str(i):
l=l+int(m)
for o in str(dec_to_binary(i)):
k=k+int(o)
if is_prime(i) and is_prime(l) and is_prime(k):
print(i)
答案 0 :(得分:0)
Several issues: Firstly, your prime check checks way too many numbers. The following implementation (derived from this answer的活动状态,在不进入严肃的高级数学而非完全愚蠢的强制数学之间进行权衡取舍是一个不错的权衡:
@lru_cache()
def is_prime(n):
"""Returns True if n is prime."""
if n in (2, 3):
return True
if n % 2 == 0 or n % 3 == 0:
return False
i, w = 5, 2
while i * i <= n:
if n % i == 0:
return False
i, w = w + i, 6 - w
return True
其次,你应该首先进行廉价检查(小得多的数字总和的素数),并且如果其他数字通过则只对数字本身进行素性检查:
def bin_sum(n):
return sum(map(int, '{0:b}'.format(n)))
def digit_sum(n):
return sum(map(int, str(n)))
a, b = map(int, input().split())
for n in range(a, b + 1):
# cheapest checks first
if is_prime(bin_sum(n)) and is_prime(digit_sum(n)) and is_prime(n):
print(n)