I wrote the following recursive code but the outcome is strange. Please Help to find the error in my C code.
For example if I take the value of n
as 10
then the output should be 2,3,5,7,11,13,17,19,23,29
but with to my code the output is 2 3 5 7 9 11 13 15 17 19
Ahh! I tried for a long time but couldn't find the problem. Here is my recursive C code:
void primeNumbers (int n)
{
if (n == 0)
return;
static int i = 2;
if (isPrime(i))
{
printf("%d ", i);
i++;
primeNumbers(n - 1);
}
else
{
i++;
primeNumbers(n);
}
}
The function to check Number is Prime or not:
bool isPrime(int n)
{
// edge case, not a base case
if (n <= 1)
return false;
static int i = 2;
if (i > n / 2)
return true;
if (n % i == 0)
return false;
i++;
return isPrime(n); // call again with i+1 value
}
Output: [if N is 10]
2 3 5 7 9 11 13 15 17 19
if I take the value of n
as 10
then the output should be 2,3,5,7,11,13,17,19,23,29
but with to my code the output is 2 3 5 7 9 11 13 15 17 19
.