Prime factors using Recursion

Help!! I have no idea on how to write the recursion code to find prime factors of numbers. The program is supposed to call the void function primeFactor() and it should be only one parameter of type long. (not sure if I did that right).
Here's what the code should look like:
Examples:
Please enter a whole number greater than 1: 5
5 = (5) :Prime!
continue? (Y/N) Y
Please enter a whole number greater than 1: 28
28 = (2)(2)(7)
continue? (Y/N)

Here's what I have so far:

#include <iostream>
#include <cstdlib>
#include <exception>
#include <cmath>

using namespace std;

int main(void)
{
long primeFactor , prime;
long whole = 0;
char again = 'N';
bool a =true;

do
{
system("cls");
cout << "Please enter a Whole number greater than 1: ";
cin >> whole;
cin.get();

if(whole < 0) // cannot be negative number not defined
{
cerr << "Whole number cannot < 1!" << endl;
cerr << "Press the \"Enter\" key to continue";
cin.get();
}

try
{
cout << whole << " = " << primeFactor << endl;

}
catch(exception e)
{
cout << "Exception:" << e.what() << endl;
cout <<"Press the \"Enter\" key to continue";
cin.get();
return EXIT_FAILURE;
}
cout << "Continue? Y\b:";
cin.get(again);
if(again == '\n')
again = 'Y';
else
cin.ignore(255,'\n'); // read past CR
putchar('\n');
}
while(again == 'Y' || again == 'y');

puts("Press the \"Enter\" key to continue");
cin.get(); // hold window open
return EXIT_SUCCESS;

// To find Prime Factors
for (int i = 2; i < sqrt(whole); i++)
{
if(whole%i==0) // if it is divisible it is non prime
{
a=false;
break;
}

if(a==false)
cout << whole << " is not a prime number" << endl;

else
cout << whole << " : Prime!" << endl;


return 0;
}
Accepting that 2 is the only even prime, your for loop should be checking odd numbers as divisors of the input integer. But this is an iterative method.
For recursion use:
n!= 1 (if n=0) ......basis formula
n!= n . (n-1)! (if n > 0)..........recurrance formula
Last edited on
Here is an example of a recursive function which calls itself from L2. You need to apply this principle to the prime algorithm.

int convert(int n)
if(n>=2) convert(n/2);
cout<<n%2;
Topic archived. No new replies allowed.