mea43 mea43 - 2 months ago 20
C++ Question

Prime factorization of integer in c++

I am trying to write a code which gives the prime factorization of given integer.
Here is my code:

#include <iostream>
#include <cmath>

using namespace std;

void primefactor(int a);

int main()
{
int n;
cout<<" Enter the value of n "<<endl;
cin>>n;
primefactor(n);
return 0;
}

void primefactor(int a){
while(a%2==0){
cout<<"2*";
a/=2;

for(int i=3; i<=sqrt(a); i+=2){
while(a%i==0){
cout<<i<<"*";
a=a/i;
}
}
if(a>2){
cout<<a<<endl;
}

}


however when i run the output at the last factor i am getting an additional * in factorization. How can I remove this?

Answer

You can use

if (a != 2)
    cout<<"2*";
else
    cout<<"2";

instead of cout<<"2*";

Comments