Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

use Python The assertion that every even number is the sum of two prime numbers

ID: 3738141 • Letter: U

Question

use Python

The assertion that every even number is the sum of two prime numbers is called Goldbach’s conjecture.

You will write a program that asks the user for an integer number, then checks if the integer is even, and finally determines two prime numbers that sum to the user’s entered integer number.

Assignment Requirements

Three functions are required:

get_input():

This function takes no parameters, but will ask the user for an integer number. It will return a valid integer. You will use an indefinite loop and exception handling like we discussed in class. It is required to catch user input error and gracefully recover. Learn about the continue keyword and how it works in a loop, it can be handy.

is_prime(n):

This function will take an integer parameter n, and return True if the number is prime, or return False if it is not prime. You can use this pseudocode for primality testing to write this function.

main():

This does the bulk of your program’s work for solving Goldbach’s conjecture. You will call get_input() and is_prime(n) from main().

Goldbach’s conjecture itself will be solved using an indefinite loop. Particularly a ‘post-test’ loop pattern. A for loop will not be accepted as part of the solution.

Sample output

A successful run:

A run recovering from errors:

If by chance the number chosen is valid, but doesn’t hold for Goldbach’s conjecture, then print:

(I’m not aware of a number for which this occurs, but handle this possible case anyways.)

Explanation / Answer

def get_input(): while True: try: inp = int(input("Please enter an even integer larger than 2 : ")) if inp % 2 != 0: print("Wrong input!") continue elif inp % 2 == 0 and inp > 2: return inp except ValueError: print("Bad input!") continue def is_prime(n): for i in range(2,n): if n % i == 0: return False return n != 1 def main(): print("This program tests the Goldbach's conjecture") flag = True n = get_input() for i in range(3, n): if is_prime(i) and flag: for j in range(i+1, n): if is_prime(j) and i+j == n and flag: print(n, " = ", i, " + ", j) flag = False if not flag: break if __name__ == '__main__': main()