@virnuls/

Goldbach

Python

One of the OCR Coding Challenges - show that every even integer greater than two is the sum of two primes

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# every positive even number greater than 2 is 
# the sum of two prime numbers

def isPrime(number):
  prime = True
  # numbers bigger than 5 ending in 2, 4, 6, 8 or 0
  # can't be prime
  if number > 5 and str(number)[-1] in "245680":
    prime = False
  else:
    # check for factors up to the square root
    factor = 2
    # there's no square root funtion in Python
    root = int(number**0.5)
    while prime and factor <= root:
      # is number divisible by factor?
      if number % factor == 0:
        prime = False
      factor += 1
  return prime

test = 0
while test < 4:
  test = input("Give me an even positive integer greater than two: ")
  # validate
  try:
    test = int(test)
    # ensure that the input is even and bigger than 2
    if test % 2 > 0 or test < 4:
      test = 0
  except:
    test = 0
# find largest odd number less than or equal to
# half of the number being checked
odd = int(test/2)
# (odd % 2 == 0) is True (i.e. 1) for even numbers
odd = odd - (odd % 2 == 0)
print("\nCombinations that add up to "+str(test)+":\n")
# count down from odd in twos (i.e. odd numbers)
for f in range(odd,2,-2):
  # if the number is prime...
  if isPrime(f):
    # check whether its complement* is also prime
    # *i.e. the number you need to add to get test
    if isPrime(test - f):
      # if so, then then that's a match
      print(f,"+",test-f)
# two is also prime, but isn't odd
if isPrime(test-2):
  print(2,"+",test-2)