我用python建表,結果還是TLE(有人說我建表有待加強但我不知道怎麼加)
用篩法被說記憶體不足(我真的不懂為什麼)
請求高人指點
建表如下:
try: while True: def primelist(start, stop): if stop < 2: return 0 else: lst = [2] for i in range(3, stop + 1): prime = True for k in range(len(lst)): if i % lst[k] == 0: prime = False break if prime == True: lst.append(i) try: while lst[0] < start: lst.pop(0) except IndexError: return 0 return len(lst) BeginEnd = [eval(i) for i in input().split()] BeginEnd.sort() print(primelist(BeginEnd[0], BeginEnd[1])) except: pass
篩法如下:
def Prime_List(): Not_Prime = [False for i in range(100000000)] Not_Prime[0] = Not_Prime[1] = True for i in range(2, 10000): if not Not_Prime[i]: j = i * (9999999 // i) for k in range(9999999 // i, i - 1, -1): if not Not_Prime[k]: Not_Prime[j] = True j -= i return Not_Prime b = Prime_List() try: while True: count = 0 a = [eval(i) for i in input().split()] for i in range(a[0], a[1] + 1): if b[i] == False: count += 1 print(count) except: pass
我範例測資都過了感覺測資壞掉,有人說TLE 是因為奇怪測資但題目條件寫 b-a <=1000,應該是BUG,不過提供你簡單一點的方法
n = input().split(" ")start = int(n[0])end = int(n[1])counter = 0for val in range(start, end + 1):if val > 1:for n in range(2, val//2 + 2):if (val % n) == 0:breakelse:if n == val//2 + 1:counter +=1print(counter)
我範例測資都過了感覺測資壞掉,有人說TLE 是因為奇怪測資但題目條件寫 b-a <=1000,應該是BUG,不過提供你簡單一點的方法
謝謝