简体   繁体   中英

How to print the middle asterisk shown from the prime factorization output by setting an end condition?

The following code inputs an integer (n) from the user and outputs the prime decomposition of n. I'm trying to set an "end" condition for the output of this part of the code but I can't:

 if(countA == 1)
        cout<<2;
    else if(countA != 0)
        cout<<2<<"^"<<countA;

An example for the correct output is:

Input: 100

Output: 2^2*5^2

But what it's printing now is without the middle asterisk (between 2 and 5):

2^25^2

The entire code:

#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, end = sqrt(n); i <= end; i = i + 2)
    {
        while(n % i == 0)
        {
            n /= i;
            countB++;
        }
        if(countB == 1)
            cout<<i<<"*";
        else if(countB != 0)
        {
            cout<<i<<"^"<< countB;
            if(!(i + 1 >= end))
                cout<<"*";
        }
    }
    if(n > 2)
        cout<<n;
    return 0;
}
#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;
}

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