Search code examples
c++coutprime-factoring

How to eliminate the extra asterisk shown from the prime factorization output?


The following code inputs an integer (n) from the user and outputs the prime decomposition of n. I need to have the following output (as an example), but can't reach it:

Input: 98

Output: 2*7^2

The actual wrong output, which has an extra "*" is:

2*7^2*
     ^

Maybe there is another solution using functions, which I don't know.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n, countA = 0, countB = 0;
    cin>>n;
    while(n % 2 == 0)
    {
        n /= 2;
        countA++;
    }
    if(countA == 1)
        cout<<2<<"*";
    else if(countA != 0)
        cout<<2<<"^"<<countA;
    for(int i = 3; i <= sqrt(n); i = i + 2)
    {
        while(n % i == 0)
        {
            n /= i;
            countB++;
        }
        if(countB == 1)
            cout<<i<<"*";
        else if(countB != 0)
        cout<<i<<"^"<<countB<<"*";
    }
    if(n > 2)
        cout<<n;
    return 0;
}

Solution

  • So one of the possible solutions to my question, according to @Jonathan Leffler's comment is as follows:

    #include <iostream>
    #include <cmath>
    using namespace std;
    
    const char *pad = "";
    int main()
    {
        int n, countA = 0, countB = 0;
        cin>>n;
        while(n % 2 == 0)
        {
            n /= 2;
            countA++;
        }
        if(countA > 0)
        {
            cout<<pad;   
            cout<<2;     
            if(countA > 1)
            {
                cout<<"^"<<countA;
            }
            pad = "*";
        }
        for(int i = 3; i <= sqrt(n); i = i + 2)
        {
            countB = 0;
            while(n % i == 0)
            {
                n /= i;
                countB++;
            }
            if(countB > 0)
            {
                cout<<pad;
                cout<<i;
                if(countB > 1)
                {
                    cout<<"^"<<countB;
                }
                pad = "*";
            }
        }
        if(n > 2)
        {
            cout<<pad;
            cout<<n;
            pad = "*";
        }
        return 0;
    }