温馨提示×

C++分解质因数的高效算法

c++
小樊
90
2024-07-14 07:57:21
栏目: 编程语言

#include <iostream>
#include <vector>
using namespace std;

void primeFactors(int n) {
    vector<int> factors;
    while (n % 2 == 0) {
        factors.push_back(2);
        n = n / 2;
    }
    for (int i = 3; i*i <= n; i = i + 2) {
        while (n % i == 0) {
            factors.push_back(i);
            n = n / i;
        }
    }
    if (n > 2) {
        factors.push_back(n);
    }
    cout << "Prime factors of the number are: ";
    for (int i = 0; i < factors.size(); i++) {
        cout << factors[i] << " ";
    }
}

int main() {
    int n;
    cout << "Enter a number to find its prime factors: ";
    cin >> n;
    primeFactors(n);
    return 0;
}

这是一个用于分解质因数的高效算法,首先判断2是否为n的因数,然后从3开始每次递增2判断是否为质因数,直到质因数的平方大于n为止。最后判断n是否大于2,如果是则加入质因数列表中。输出结果为输入的数的所有质因数。

0