Twin primes: Difference between revisions

Line 1,166:
=={{header|Python}}==
 
<lang python>prime_dictprimes = {}[2, 3, 5, 7, 11, 13, 17, 19]
 
 
def is_primecount_twin_primes(nlimit: int) -> boolint:
global prime_dictprimes
if nlimit >= 23primes[-1]:
ram_limit = primes[-1] + 90000000 - len(primes)
reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1
 
while reasonable_limit < limit:
global prime_dict
ram_limit = primes[-1] + 90000000 - len(primes)
if n not in prime_dict:
if ram_limit > primes[-1]:
prime_dict[n] = is_prime_(n)
reasonable_limit = min(limit, primes[-1] ** 2, ram_limit)
if n % x == 0else:
reasonable_limit = min(limit, primes[-1] ** 2)
 
sieve = list({x for prime in primes for x in
if n >= 23:
for x in range(nprimes[-1] *+ 2,prime n- *(primes[-1] 50% prime), nreasonable_limit, prime)}):
prime_dictprimes += [x] =- False1 for #i, Imitationx ofin enumerate(sieve) ofif Eratosthenesi and x - 1 != sieve[i - 1] and x - 1 < limit]
 
count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y])
return prime_dict[n]
 
 
def is_prime_(n: int) -> bool:
for x in [2, 3, 5, 7, 11, 13, 17, 19]:
if n % x == 0:
return n == x
 
i = 23
while i ** 2 <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
 
return True
 
 
def count_twin_primes(limit: int) -> int:
p2 = True
p1 = False
count = 0
for i in range(5, limit):
p3 = p2
p2 = p1
p1 = is_prime(i)
if p3 and p1:
count += 1
 
return count
Line 1,212 ⟶ 1,193:
def test(limit: int):
count = count_twin_primes(limit)
print(f"Number of twin prime pairs less than {limit} is {count}\n")
 
 
test(10)
if __name__ == '__main__':
test(10100)
test(1001000)
test(100010000)
test(10000100000)
test(1000001000000)
test(100000010000000)
test(10000000100000000)</lang>
test(100000000)</lang>
{{out}}
<pre>Number of twin prime pairs less than 10 is 2