Goldbach\'s Conjecture I am being asked to take two user input limits and print
ID: 644404 • Letter: G
Question
Goldbach's Conjecture
I am being asked to take two user input limits and print out the prime numbers that sum to that number.
Example:
Enter lower limit: 4
Enter upper limit: 12
(4 = 2 + 2), (6 = 3 + 3), (8 = 3 + 5), (10 = 3 + 7 = 5 + 5), (12 = 5 + 7)
The maximum number of pairs = 2
My code works except that it considers 15 as a prime number and thus throws off my max pairs.
Can I get a fix on it?
Code:
def is_prime(n):
limit = int (n ** 0.5) + 1
div = 2
while (div < limit):
if (n % div == 0):
return False
div = div + 1
return True
def main():
#Input limits
low = eval (input("Enter lower limit: "))
high = eval (input("Enter upper limit: "))
#Check limits
while (low % 2 != 0) or (low < 4) or (high % 2 != 0) or (low > high):
low = eval (input("Enter lower limit: "))
high = eval (input("Enter upper limit: "))
num = low
maxpairs = 0
#Print pairs
for i in range (num, high + 2, 2):
x = 2
half = i / 2
pairs = 0
print (i, end = " ")
while (x <= half):
if (is_prime (x)):
x = x
y = i - x
if (is_prime (y)):
pairs += 1
print ("=", x, "+", y, end = " ")
if (maxpairs < pairs):
maxpairs = pairs
x = x + 1
print ()
print ("The maximum number of pairs = ", maxpairs)
main()
Explanation / Answer
#include<stdio.h>
#include<math.h>
int primecheck(long int x);
main()
{
long int a,b,c;
int i,j,k;
label: printf("Enter the number: ");
scanf("%ld",&a);
if ((a%2)==1)
{
printf(" That's an odd number you dumbo! Goldbach's Conjecture involves an even number! ");
goto label;
}
for (b=2;b<a;++b)
{
for (c=2;c<a;++c)
{
j=primecheck(b),k=primecheck(c);
if ((j==0) && (k==0) && (b+c==a) && (b<=c))
printf(" %4ld + %4ld = %4ld",b,c,a);
}
}
printf(" ");
}
int primecheck(long int x)
{
long int i=2;
while (i<x)
{
if ((x%i)==0)
break;
++i;
}
if (i==x)
return(0);
else
return(1);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.