Search code examples
cprimes

Goldbach theory in C


I want to write some code which takes any positive, even number (greater than 2) and gives me the smallest pair of primes that sum up to this number. I need this program to handle any integer up to 9 digits long.

My aim is to make something that looks like this:

Please enter a positive even integer ( greater than 2 ) :
10
The first primes adding : 3+7=10.
Please enter a positive even integer ( greater than 2 ) :
160
The first primes adding : 3+157=160.
Please enter a positive even integer ( greater than 2 ) :
18456
The first primes adding : 5+18451=18456.

I don't want to use any library besides stdio.h. I don't want to use arrays, strings, or anything besides for the most basic toolbox: scanf, printf, for, while, do-while, if, else if, break, continue, and the basic operators (<,>, ==, =+, !=, %, *, /, etc...). Please no other functions especially is_prime.

I know how to limit the input to my needs so that it loops until given a valid entry.

So now I'm trying to figure out the algorithm.

I thought of starting a while loop like something like this:

  #include <stdio.h>
long first, second, sum, goldbach, min;
long a,b,i,k; //indices

int main (){

    while (1){
        printf("Please enter a positive integer :\n");
        scanf("%ld",&goldbach);
        if ((goldbach>2)&&((goldbach%2)==0)) break;
        else printf("Wrong input, ");
        }

    while (sum!=goldbach){
        for (a=3;a<goldbach;a=(a+2))
            for (i=2;(goldbach-a)%i;i++)
                first = a;
        for (b=5;b<goldbach;b=(b+2))
            for (k=2;(goldbach-b)%k;k++)
        sum = first + second;
        }
}

Solution

  • Have a function to test primality

    int is_prime(unsigned long n)
    

    And then you only need to test whether a and goldbach - a are both prime. You can of course assume a <= goldbach/2.

    And be sure to handle goldbach = 4 correctly.

    If the requirements don't allow defining and using your own functions, ignore them first. Solve the problem using any functions you deem helpful and convenient. When you have a working solution using disallowed functionality, then you start replacing that with allowed constructs. Self-defined functions can be inlined directly, replacing the return with an assignment, so instead of if (is_prime(a)), you have the code to determine whether a is prime and instead of returning the result you assign it is_prime = result; and test that variable if (is_prime). Where you have used library functions, reimplement them yourself - efficiency doesn't matter much - and then inline them too.