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);
#include <iostream>
usingnamespace 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);
}
#include <iostream>
usingnamespace std;
bool preDivisor( int n, int i )
{
if ( i < 2 ) returnfalse;
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);
}