Creating a recursive function with no parameters does not make much sense, because the whole point of recursion is that the function arguments change with every level of recursion.
If you want the function generatePrime
to take no parameters, but to return the next prime whenever it is called, then the function must remember the last value that it returned. This can be accomplished by remembering this value in a variable with static storage duration, for example a global variable or a static
local variable. Since you need to access this variable both from the function main
and from the function generatePrime
, I recommend a global variable.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
static int next;
//This function returns true if the number is prime,
//otherwise false. This is a very simple, inefficient
//implementation. Better, more efficient algorithms exist,
//such as the Sieve of Eratosthenes.
bool isprime( int num )
{
if ( num < 2 )
return false;
int max = (int)sqrt( num ) + 1;
if ( max >= num )
max = num - 1;
for ( int i = 2; i <= max; i++ )
{
if ( num % i == 0 )
return false;
}
return true;
}
int generatePrime()
{
while ( !isprime( next ) )
next++;
return next++;
}
int main( void )
{
int low, high, i;
printf( "Please enter low and high value: " );
if ( scanf("%d %d", &low, &high) != 2 )
{
printf( "invalid input!\n" );
exit( EXIT_FAILURE );
}
next = low + 1;
while ( ( i = generatePrime() ) < high )
printf( "%d\n", i );
}
This program has the following output:
Please enter low and high value: 2 30
2
3
5
7
11
13
17
19
23
29
Please enter low and high value: 100 200
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
Note that this program will calculate one more prime number than it prints, which is a bit wasteful. However, since your task requires the function generatePrime
to not take any parameters, I don't see any simple way to fix this.