Hi all. I\'m attempting to write a program for a computer science class: http://
ID: 3672531 • Letter: H
Question
Hi all. I'm attempting to write a program for a computer science class: http://www.cs.utexas.edu/users/mitra/csSpring2016/cs303/assgn/assgn5.html
Essentially, it's a program that proves the Goldbach conjecture for a user-defined range, by printing any prime numbers that add up to a number within that range.
My test range is 4-100. For the first two even results, it works as intended. However, any numbers past 8 do not display. In fact, nothing displays -- no error or anything.
I've included my code on Pastbin (http://pastebin.com/VjGzPKzm). What am I missing here? How should it be solved?
Thanks for any help!
Explanation / Answer
There was an error with indentation in is_prime function. Fixed it. Updated output formatting.
def goldbach():
def is_prime(n):
if (n==1):
return False
limit = int(n**.5)+1
divisor = 2
while (divisor < limit):
if (n % divisor == 0):
return False
# Indentation of following statement was incorrect
divisor += 1
return True
# Input starting and ending points
low = eval (input ("Enter the lower limit: "))
high = eval (input ("Enter the upper limit: "))
# Insure that input meets requirements
if (low < 4) or (low > high) or (low % 2 != 0) or (high % 2 != 0):
low = eval (input ("Enter the lower limit: "))
high = eval (input ("Enter the upper limit: "))
# Compute and print results
counter = low
while (counter <= high):
num = 2
# tracking of first print
first_print = True
while (num <= counter/2):
sub_num = counter - num
if (is_prime(num) and is_prime(sub_num)):
if first_print:
print (counter ,"=", num ,"+", sub_num , end ='')
first_print = False
else:
print(' =', num, '+', sub_num, end = '')
num = num + 1
counter = counter + 2
print()
goldbach()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.