Advertisement
cookchar

Circular Primes (Project Euler #35)

Jul 23rd, 2018
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. def isPrime(p):
  2.     if primes[len(primes) - 1] ** 2 < p:
  3.         print("Error: Attempted to prime check a number with an improper prime list!")
  4.         return False
  5.  
  6.     for q in primes:
  7.         if q**2 > p:
  8.             return True
  9.  
  10.         if not p % q:
  11.             return False
  12.  
  13. def checkRotations(p):
  14.     s = str(p)
  15.     rotations = len(s) - 1
  16.  
  17.     for r in range(rotations):
  18.         s += s[0]
  19.         s = s[1:]
  20.  
  21.         if not isPrime(int(s)):
  22.             return False
  23.  
  24.     return True
  25.  
  26. primes = [2]
  27. p = 3
  28. n = 1
  29. show = False
  30.  
  31. try:
  32.     ceiling = int(input("Enter an upper bound for searching for primes: "))
  33. except ValueError:
  34.     print("Error: Not a natural number!")
  35.     exit()
  36.  
  37. if str(input("Enable individual printout? [Y/n]: ")).upper() == "Y":
  38.     show = True
  39.  
  40. if show:
  41.     print(primes[0], end = "\t")
  42.  
  43. while p < ceiling:
  44.     if isPrime(p):
  45.         primes.append(p)
  46.         n += 1
  47.  
  48.         if show:
  49.             print(str(p), end = "\t")
  50.             if not n % 10:
  51.                 print()
  52.  
  53.     p += 2
  54.  
  55. print("\n" + str(len(primes)) + " primes found overall.")
  56.  
  57. c = 0
  58.  
  59. for p in primes:
  60.     if checkRotations(p):
  61.         if show:
  62.             print(p, "is a circular prime.")
  63.        
  64.         c += 1
  65.  
  66. print(c, "circular primes found overall.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement