Reputation: 41
I need to generate prime twins in python but I can only use basics (if, elif, else, for, print. I cannot use while, def, return or break etc.
I wrote this code but it only works under 100, If I want a range up to 1000 it doesn't work and I have no idea how to do it without putting there hundreds ifs'.
Could you please help me?
I tried this:
for i in range (2,100):
j=i+2
primetw=True
if i%2 == 0 or i%3==0 or i%5==0 or i%7==0:
primetw=False
if j%2 == 0 or j%3==0 or j%5==0 or j%7==0:
primetw=False
if i==3 or i==5 or j==5:
primetw=True
if primetw==True:
print(i,j)
Which has this output:
3 5
5 7
11 13
17 19
29 31
41 43
59 61
71 73
Upvotes: 0
Views: 1693
Reputation: 41
I figured it out this way.
for i in range (3,101):
twin = True
for j in range (2,i):
if (i % j) == 0 or ((i+2) % j) == 0:
twin = False
if twin == True:
print (i,i+2)
Output is:
3 5
5 7
11 13
17 19
29 31
41 43
59 61
71 73
Upvotes: 0
Reputation: 382
Here you have an example implementation.
First calculates all prime numbers under N using the sieve of Eratosthenes, and then it finds twin primes. It's probably not the most efficient implementation by I think is good enough for educational purposes.
N = 1000
##
# Find primes using the sieve of Eratosthenes
##
isPrime = [False, False]
for _ in range(2, N):
isPrime.append(True)
for candidate in range(2, N):
if isPrime[candidate]:
for i in range(candidate+1, N):
if i % candidate == 0:
isPrime[i] = False
primes = []
for i, v in enumerate(isPrime):
if v:
primes.append(i)
##
# Calculate twin primes
##
twinPrimes = []
for prime in primes:
if prime + 2 in primes:
twinPrimes.append((prime, prime + 2))
print(twinPrimes)
Upvotes: 1