Reputation: 43
I have written a functions that outputs the prime factors of a number entered by the user. The output i am getting is correct, however the output is backwards.
For example the input is 1776: output => 2 x 2 x 2 x 2 x 3 x 37 x
The output I'm looking for is => 37 x 3 x 2 x 2 x 2 x 2
how can I inverse the output and remove the extra multiplication symbol (x) behind 37.
void primefactor(int x)
{
// initalize a int with a static value of 2
static int i=2;
// if i less then or equal to x
if(i<=x)
{
// while x%i doess equal 0 you have found a factor print factor
while(x%i ==0)
{
cout<<i<<" x ";
// x takes a new value of x / i
x=x/i;
}
// increment i and call fuction again
i++;
primefactor(x);
}
}
Upvotes: 0
Views: 129
Reputation: 597111
To remove the trailing x
, you can print it out conditionally:
while ((x % i) == 0)
{
std::cout << i;
x /= i;
if (x > 1)
std::cout << " x ";
}
Also, you can remove the static
if you make i
be an input parameter instead:
void primefactor(int x, int i = 2)
{
...
primefactor(x, ++i);
...
}
But, to reverse the output is a little tricky for this kind of recursion. If you can use an iterative loop instead of a recursive loop, then you can use a local std::vector
to accumulate the factors and then reverse their order before printing them, eg:
#include <vector>
#include <algorithm>
void primefactor(int x)
{
std::vector<int> v;
int i = 2;
while (i <= x)
{
while ((x % i) == 0)
{
v.push_back(i);
x /= i;
}
++i;
}
if (!v.empty())
{
std::reverse(v.begin(), v.end());
std::cout << v[0];
for(size_t idx = 1; idx < v.size(); ++idx)
std::cout << " x " << v[idx];
}
}
But, if you absolutely need a recursive function, you can still use a std::vector
, just pass it around to each iteration, eg:
void primefactor_loop(int x, int i, std::vector<int> &v)
{
if (i <= x)
{
while ((x % i) == 0)
{
v.push_back(i);
x /= i;
}
primefactor_loop(x, ++i, v);
}
}
void primefactor(int x)
{
std::vector<int> v;
primefactor_loop(x, 2, v);
if (!v.empty())
{
std::reverse(v.begin(), v.end());
std::cout << v[0];
for(size_t idx = 1; idx < v.size(); ++idx)
std::cout << " x " << v[idx];
}
}
Upvotes: 1