微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何通过设置结束条件打印素数分解输出中显示的中间星号?

如何解决如何通过设置结束条件打印素数分解输出中显示的中间星号?

以下代码用户输入一个整数(n)并输出n的素数分解。我正在尝试为这部分代码输出设置“结束”条件,但我不能:

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

正确输出的示例是:

输入:100

输出2^2*5^2

但它现在打印的是没有中间星号(2 到 5 之间):

2^25^2

完整代码

#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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。