vendredi 29 janvier 2016

C - Print list of Prime Numbers (recursion)

I'm having some problems with this C programming assignment that I have in school. I'm supposed to return the prime numbers from within a given range, and it has to be done using recursion.

The code I've got so far is this:

#include <stdio.h>
#include <stdlib.h>

int primeNumberList(int n, int m, int z);

int main()
{
    int n1 = 0,
        n2 = 10,
        d = 2;

        printf("n1 = %d | n2 = %d | d = %d\n\n", n1, n2, d);

        printf("Prime Numbers between %d and %d are: \n", n1, n2);

        primeNumberList(n1, n2, d);

        printf("\n\n");


    return 0;
}


int primeNumberList(int n, int m, int z){
    int notPrime = 0;

    if(n <= 1){
        primeNumberList(n+1, m, z);
    }
    else if(n < m)
    {
        if(z <= n/2)
        {
            if(n%z == 0)
            {
            notPrime = 1;
            z = 2;
            }
            else
            {
            primeNumberList(n, m, z+1);
            }
        }
        if(notPrime == 0)
        {
            printf("%d ", n);
        }
        primeNumberList(n+1, m, z);
    }
}

What happens when I run this, is that after it's gone through all the numbers up to the limit (in the function it's 'm'(n2 in main)) it won't break the recursion, but somehow manage to withdraw numbers from n, and keeps giving some other numbers that are not prime numbers. When I run it in debug, it seems to be looping at the end, but there's nothing there to loop... I've tried adding a "return 0;" or even a printf with some text, but it ignores it completely.

Can anyone see what I've done wrong here? Why doesn't it stop when "n < m"?

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire