I made a fun version of this.
Code:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
void factor(int, vector<int>&);
int main(int argc, const char* argv[])
{
// Check the number of parameters
if (argc != 2)
{
cout << "Usage: " << argv[0] << " number_to_factor" << endl;
return 0;
}
// Convert the parameter to an integer
stringstream n_stream;
int n;
n_stream << argv[1];
if (!(n_stream >> n)) {
cout << "Invalid integer: " << argv[1] << endl;
return 0;
}
vector<int> primes;
// Factor the number
factor(n, primes);
cout << endl;
return 0;
}
void factor(int n, vector<int> &primes)
{
if (n < 2)
return;
for (vector<int>::iterator i = primes.begin(); i != primes.end(); i++)
{
int p = *i;
if (n % p == 0) {
cout << p << " ";
factor(n / p, primes);
return;
}
}
int new_p = (primes.size() > 0) ? primes.back() : 2;
while (n % new_p != 0)
new_p++;
primes.push_back(new_p);
cout << new_p << " ";
factor(n / new_p, primes);
}
Yes, this can be made into a loop very easily, but where's the fun in that?
An interesting aside: It displays the complete prime factorization (with prime repeats), but the primes vector now contains only the unique primes that divide the number.