Question

I have a function to determine if a given number is prime. I have been attempting to write a function to find the next prime number after the given number. The problem is that it only works on certain numbers.

I pretty much just gave it my best guess so if its poorly written that would be why.

# include <stdio.h>

int next(int);
int is_prime(int);

int main()
{
        int num;
        printf("Enter a number\n");
        scanf("%d", &num);

printf("next prime is %d\n",  next(num));

return 0;

This next part is to check if its prime

is_prime(int n)
{
        int i, test=0;

        for (i=2; i<=n/2; i++)
        {
                if(n%i==0)
                {
                        test++;
                        break;
                }
        }
        if (test==0)
                return 1;
         else
                return 0;
}

now the function to check for the next prime number

int next(int x)
{
        int y, i;

        for(i=x+1; i>0;  i++)
        {
                if(is_prime(i)==1)
                                return i;
                                break;
        }
}

I don't know if it matters but some samples that worked where 6, 10 and 12 but 7, 8, 13, and 14 did not work.

Was it helpful?

Solution

Your problem is the break statement, remove it.

int next(int x)
{
    int y, i;

    for(i=x+1; i>0;  i++)
    {
        if(is_prime(i)==1)
            return i;
            break;       //delete this line
    } 
}

What is happening is that, after every first test, you are immediately breaking out of the loop. Which is why numbers like 6, 10, and 12 are working. That is because the next number immediately after is a prime number. For every other case where the next immediate number is not prime, this won't work; it will break if a prime isn't reached. If you want to execute more than one statement in an if-branch, you must wrap them in {} braces.

This is the correct form for multiple statements in an if-branch:

if(is_prime(i)==1)
{
    return i;
    break;  
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top