Home > Enterprise >  Next Prime number function problem when I use a recursive function
Next Prime number function problem when I use a recursive function

Time:08-19

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:

#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.

CodePudding user response:

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);
}
  • Related