Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Next Prime number function problem when I use a recursive function

I have a problem with a recursive function. The function must return the next prime number.

As parameter I give a number an it must return the number if is prime, or the next prime number.
The function works fine in almost cases, when I comment the recursion it shows a list of numbers from one to hundred and allocate the primes. The rest return O.
But when I insert the recursive in some cases shows a next prime that is not prime, case of 35 and 95 for example.
when I put 4 it show the next prime that is 7.
but when it reaches 32 it shows 35 that was not correct. It should shows 37.
I don’t know were the problem is.

The code is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <stdio.h>
#include <unistd.h>

int     ft_find_next_prime(int nb)
{
    int     i;
    int     z;

    i = nb - 1;
    z = nb;

    while (i > 1)
    {
        if ((z % i) == 0)
        {
             //return (0);
             ft_find_next_prime(++z);
        }
        else
            i--;
    }
    return (z);
}

int     main(void)
{
    int     i;

    i = 1;
    printf("\n\tNUMERO\t---\tSIGIENTE PRIMO\n");
    printf("-----------------------------------------------------\n");
    while (i <= 100)
    {
        printf("\t%i\t---\t%i\n", i, ft_find_next_prime(i));
        i++;
    }
    return (0);
}

Thanks so much in advance.

>Solution :

The only thing missing in the recursive code is the return keyword, or an assignment of the variable z. The reeason is that the z passed into parameter is a copy, not the original z variable.

int ft_find_next_prime(int nb)
{
    int     i;
    int     z;

    i = nb - 1;
    z = nb;

    while (i > 1)
    {
        if ((z % i) == 0)
        {
            //return (0);
            return ft_find_next_prime(++z);
            // or : z = ft_find_next_prime(++z);
        }
        else
            i--;
    }
    return (z);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading