Guest User

Prime Pair Connection

a guest
Jun 13th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. from primefac import primes
  3. from math import log
  4.  
  5. '''
  6. Prime pair connection
  7. Project Euler: Problem 134
  8.  
  9. Consider the consecutive primes p1 = 19 and p2 = 23. It can be verified that 1219 is the smallest number such that the last digits are formed by p1 whilst also being divisible by p2.
  10.  
  11. In fact, with the exception of p1 = 3 and p2 = 5, for every pair of consecutive primes, p2 > p1, there exist values of n for which the last digits are formed by p1 and n is divisible by p2. Let S be the smallest of these values of n.
  12.  
  13. Find ∑ S for every pair of consecutive primes with 5 ≤ p1 ≤ 1000000.
  14.  
  15. '''
  16.  
  17. def sum_prime_pair(limit):
  18.     twin = twin_primes(limit)
  19.     twin.remove((3, 5))
  20.     total = 0
  21.     for pair in twin:
  22.         total += p1_div_p2(pair)
  23.     return total
  24.  
  25.  
  26. def twin_primes(limit):
  27.     prime_list = primes(limit)
  28.     twin_lst = []
  29.     p1 = prime_list.pop(0)
  30.     for p2 in prime_list:
  31.         if p1 + 2 == p2:
  32.             twin_lst.append((p1, p2))
  33.         p1 = p2
  34.     return twin_lst
  35.  
  36.  
  37. def p1_div_p2(twin_primes):
  38.     p, q = twin_primes
  39.     k = 10**int(log(p, 10)+1)
  40.     m = 2*pow(k, p, q) % q
  41.     return p + k*m
  42.  
  43.  
  44. if __name__ == '__main__':
  45.     print sum_prime_pair(10**6)
Advertisement
Add Comment
Please, Sign In to add comment