簡體   English   中英

如何消除從素數分解 output 中顯示的額外星號?

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

以下代碼從用戶輸入一個 integer (n) 並輸出 n 的素數分解。 我需要有以下 output (例如),但無法達到:

輸入: 98

Output: 2*7^2

實際錯誤的 output,其中有一個額外的“*”是:

2*7^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; 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;
}

而不是無條件地打印它:

cout<<i<<"^"<<countB<<"*";

你可以測試它是否是最后一個數字。 示例(適用於任何需要的地方):

for(int i = 3, end = sqrt(n); i <= end; i = i + 2) {
    // ...
    cout << i << '^' << countB;
    if(i + 2 <= end) cout << '*';

因此,根據@Jonathan Leffler 的評論,我的問題的可能解決方案之一如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM