roheet
roheet

Reputation: 13

Representing a number as the sum of two prime numbers

What's wrong with my code? Why am I not getting any output? I'm practicing for embedded system.

running code screenshot

#include <stdio.h>

int checkP (int n)
{
    for (int i=2; i<n; i++)
        if(n%i==0)
            return (0);
    return (1);
}

int nextP (int n)
{
    do
     n++;
    while (!checkP(n));
    return n;
}

int main (void)
{
    int x = 34;  //user input
    for (int i = 2; i < x - 1; i = nextP(i))
    {
        if (checkP(x - 1)) {
            printf ("\n %d + %d", i, x-1);
        }
    }
}

Upvotes: 0

Views: 226

Answers (1)

mch
mch

Reputation: 9814

x-1 is always 33, you want to use x-i, so that the sum of i and x-i is x.

The if should look like that:

if (checkP(x - i)) {
     printf ("\n %d + %d", i, x-i);
}

https://ideone.com/jAIfa2

Output:

 3 + 31
 5 + 29
 11 + 23
 17 + 17
 23 + 11
 29 + 5
 31 + 3

Upvotes: 1

Related Questions