c ++中整数的素数因子分解

时间:2016-09-20 05:46:25

标签: c++

我正在尝试编写一个代码,该代码给出给定整数的素数因子分解。 这是我的代码:

#include <iostream>
#include <cmath>

using namespace std;

void primefactor(int a);

int main()
{
    int n;
    cout<<" Enter the value of n "<<endl;
    cin>>n;
    primefactor(n);
    return 0;
}

void primefactor(int a){
    while(a%2==0){
        cout<<"2*";
        a/=2;

    for(int i=3; i<=sqrt(a); i+=2){
        while(a%i==0){
            cout<<i<<"*";
            a=a/i;
        }
    }
    if(a>2){
        cout<<a<<endl;
    }

}

然而,当我在最后一个因素运行输出时,我在分解中获得了额外的*。我该如何删除?

2 个答案:

答案 0 :(得分:0)

您可以使用

if (a != 2)
    cout<<"2*";
else
    cout<<"2";

而不是cout<<"2*";

答案 1 :(得分:0)

我遇到了同样的问题,并用 goto 语句解决了这个问题。

#include <iostream>
#include <math.h>

using namespace std;

void primeFactorization(int number) {

cout << number << ": ";

// WHILE number is even
while (number % 2 == 0) {
   // SET number = number / 2
    number = number / 2;
   // PRINT 2
    cout << 2 << " " ;
    // END WHILE
}
//  GOTO TERMINAL
reloop:
// FOR factor in 3 to the sqrt(number), by 2
for (int factor = 3; factor <= sqrt(number); factor = factor + 2) {
    // IF number modular factor equals 0 THEN
    if (number % factor == 0) {
    // PRINT factor
        cout << factor << " " ;
    // SET number = number / factor
        number = number / factor;
    // GOTO INITIAL 
        goto reloop;
    // END IF
    }
    // END FOR
}
//IF number > 2 THEN
if (number > 2) {
    //PRINT number
    cout << number;
    //END IF
}
cout << endl;
}

int main() {

int usersNumber;
bool userWants2Play = true;

while (userWants2Play) {

cout << "Please enter a number to be factored: " ;
cin >> usersNumber;

primeFactorization(usersNumber);

    cout << "Do you want to play again? 1 or 0: " ;
    cin >> userWants2Play;
}

return 0;
}

goto 语句允许新的奇数再次通过循环。这样可以打印奇数素数因子,并且如果因子存在,则允许再次考虑新旧数。

如果这有帮助,请告诉我!我认为这是没有错误的。