简体   繁体   中英

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?

I had the same issue and solved it with a goto statement.

#include <iostream>
#include <math.h>

using namespace std;

void primeFactorization(int number) {

cout << number << ": ";

// WHILE number is even
while (number % 2 == 0) {
   // SET number = number / 2
    number = number / 2;
   // PRINT 2
    cout << 2 << " " ;
    // END WHILE
}
//  GOTO TERMINAL
reloop:
// FOR factor in 3 to the sqrt(number), by 2
for (int factor = 3; factor <= sqrt(number); factor = factor + 2) {
    // IF number modular factor equals 0 THEN
    if (number % factor == 0) {
    // PRINT factor
        cout << factor << " " ;
    // SET number = number / factor
        number = number / factor;
    // GOTO INITIAL 
        goto reloop;
    // END IF
    }
    // END FOR
}
//IF number > 2 THEN
if (number > 2) {
    //PRINT number
    cout << number;
    //END IF
}
cout << endl;
}

int main() {

int usersNumber;
bool userWants2Play = true;

while (userWants2Play) {

cout << "Please enter a number to be factored: " ;
cin >> usersNumber;

primeFactorization(usersNumber);

    cout << "Do you want to play again? 1 or 0: " ;
    cin >> userWants2Play;
}

return 0;
}

The goto statement allows for the new odd number to go through the loop again. This lets the odd prime factors print and allows the new old number to be factored again, if the factor exists.

Let me know if this helped! I think it is error free.

You can use

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

instead of cout<<"2*";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM