Advertisement
helton

Goldbach Conjecture in Python

Jul 13th, 2013
658
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """
  2.   Numerical solution to Goldbach’s conjecture.
  3.  
  4.   Author: Helton Carlos de Souza <heltoncarlossouza@hotmail.com>
  5.  
  6.   The Goldbach’s Conjecture:
  7.   1) Every even number greater than 2 is the sum of two primes
  8.   2) Every odd number greater than 5 is the sum of three primes.
  9. """
  10.  
  11.  
  12. def divisors(n):
  13.     return [x for x in range(1, n + 1) if n % x == 0]
  14.  
  15. def is_prime(n):
  16.     return divisors(n) == [1, n]
  17.  
  18. def prime_range(n):
  19.     return [x for x in range(2, n + 1) if is_prime(x)]
  20.  
  21. def goldbach_conjecture(n):
  22.     if n % 2 == 0:
  23.         if n > 2:
  24.             return [(x, y) for x in prime_range(n) for y in prime_range(n) if x + y == n and x <= y]
  25.         else:
  26.             raise ValueError('Even numbers must be greater than 2')
  27.     else:
  28.         if n > 5:
  29.             return [(x, y, z) for x in prime_range(n) for y in prime_range(n) for z in prime_range(n) if x + y + z == n and x <= y <= z]
  30.         else:
  31.             raise ValueError('Odd numbers must be greater than 5')
  32.  
  33. def show_goldbach_conjecture(n):
  34.     tuples_list = goldbach_conjecture(n)
  35.     print(str(n), end='')
  36.     for t in tuples_list:
  37.         print(" = ", end='')
  38.         for index, number in enumerate(t):
  39.             if index == len(t) - 1:
  40.                 print(str(number), end='')
  41.             else:
  42.                 print(str(number) + " + ", end='')
  43.     print()
Advertisement
RAW Paste Data Copied
Advertisement