Using Recursion to List all Prime numbers from 1 to n

Hello everyone. I am struggling to use recursion in order to list all the prime numbers from 1 through the inputted variable. If anyone can help me out, I would greatly appreciate it as this is practice for my class.

/* List ALL prime numbers from 1 through n. */

#include <iostream>
using namespace std;

void recursion(int n) {
if(n > 2) recursion(n - 1);
if (n == 1 || n == 2) cout << n << " ";
for (int i = 2; i < n; ++i) {
if (n % i != 0) cout << n << " ";
}
}

int main() {
int k;
cout << "Enter a value: ";
cin >> k;
recursion(k);

exit(0);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

void recursion( int n )
{
   if (n > 2 ) recursion( n - 1 );
   for ( int i = 2; i < n; ++i )
   {
      if ( n % i == 0 ) return;
   }
   cout << n << '\n';
}

int main()
{
   int k;
   cout << "Enter a value: ";
   cin >> k;
   recursion(k);
}



Bit more recursion:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

bool preDivisor( int n, int i )
{
   if ( i < 2 ) return false;
   return n % i == 0 || preDivisor( n, i - 1 );
}

void recursion( int n )
{
   if (n > 2 ) recursion( n - 1 );
   if ( !preDivisor( n, n - 1 ) ) cout << n << '\n';
}

int main()
{
   int k;
   cout << "Enter a value: ";
   cin >> k;
   recursion(k);
}
Last edited on
Topic archived. No new replies allowed.