Advertisement
makispaiktis

Problem 5 - Twin Primes

Jul 5th, 2021 (edited)
973
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. # Function 1 - Find the primes
  2. def findPrimes(limit):
  3.     primes = [2, 3]
  4.     for n in range(4, limit+1):
  5.         isPrime = True
  6.         for prime in primes:
  7.             if n % prime == 0:
  8.                 isPrime = False
  9.                 break
  10.         if isPrime:
  11.             primes.append(n)
  12.     print("Primes until " + str(limit) + " ----> " + str(primes))
  13.     print()
  14.     return primes
  15.  
  16. # FUNCTION 2 - Find the twin primes in a given primes list
  17. def twinPrimes(limit):
  18.     primes = findPrimes(limit)
  19.     counter = 0
  20.     print("***********************************************")
  21.     for i in range(len(primes)-1):
  22.         if primes[i+1] - primes[i] == 2:
  23.             counter += 1
  24.             print("Twins: " + str(primes[i]) + " and " + str(primes[i+1]))
  25.     print("There are " + str(counter) + " pairs of twin primes from 2 to " + str(limit))
  26.     print("***********************************************")
  27.     print()
  28.     return counter
  29.  
  30. # MAIN FUNCTION
  31. limit1 = 10**3
  32. counter1 = twinPrimes(limit1)
  33. limit2 = 10**4
  34. counter2 = twinPrimes(limit2)
  35. limit3 = 10**5
  36. counter3 = twinPrimes(limit3)
  37. print("From 1 to " + str(limit1) + ": " + str(counter1) + " pairs of twin numbers")
  38. print("From 1 to " + str(limit2) + ": " + str(counter2) + " pairs of twin numbers")
  39. print("From 1 to " + str(limit3) + ": " + str(counter3) + " pairs of twin numbers")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement