簡體   English   中英

C++中的主要因素(程序錯誤)

[英]Prime Factors in C++(Error in program)

  • 當我輸入6我只得到2
  • 當我輸入91我只得到7

然而:

  • 當我輸入18我得到2 3 3
  • 當我輸入2121 (即 3*7*101)時,我得到3 7

我似乎無法找出問題所在。 有人有什么建議嗎?

#include<iostream>
using namespace std;

bool is_prime( int fac )
{
    int i;
    bool found;
    found=true;

    for( i = 2; i < fac; i++ )
    {
        if ( fac % i == 0 && found)
        {
            found=false;
            break;
        }
    }
    return found;
}

void prime_factors(int x)
{
    int i;
    for ( i = 2; i < x; i++ )
    {
        if ( is_prime(i) )
        {
            while ( x % i == 0 )
            {
                cout << i << " ";
                x = x / i;
            }
        }
    }
}


int main(){
    int x;
    cin>>x;
    prime_factors(x);
}

除了代碼縮進問題(我為您解決了這些問題)之外,這里還有兩個主要問題:

  1. 您正在prime_factors()函數中修改x ,並且您的循環測試x以了解何時提前退出。 您應該制作x的副本,以免這樣做。
  2. 你不是在循環之間恢復x

您還可以將is_prime()函數中正在執行的測試數量減少一半。

更正的代碼清單


#include<iostream>
using namespace std;

bool is_prime( int fac )
{
    int i;
    bool found = true;

    for( i = 2; i < fac; i++)
    {
        if ( fac % i == 0 )
        {
            found=false;
            break;
        }
    }
    return found;
}

void prime_factors( int x )
{
    int i;
    int test;
    for ( i = 2; i <= x; i++ )
    {
        test = x;
        if ( is_prime(i) )
        {
            while ( test % i == 0 )
            {
                cout << i << " ";
                test /= i;
            }
        }
    }
}


int main(){
    int x;
    cin >> x;
    prime_factors(x);
}

樣本輸出


./a.out 
100000
2 2 2 2 2 5 5 5 5 5 

./a.out 
6
2 3 

./a.out 
1001
7 11 13 

暫無
暫無

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

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