You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于最小质因子函数编写C++递归程序实现正整数质因数分解

实现思路

  • 你已经实现的smallFactor函数逻辑完全正确,无需修改,我们只需要新增符合要求的递归函数即可,原来的isPrime函数可以直接删除
  • 递归函数的核心逻辑分为两个分支:
    1. 递归终止条件:调用smallFactor获取当前数的最小质因数,如果这个值等于当前数本身,说明当前数已经是质数,直接输出它即可结束递归
    2. 递归推进逻辑:如果最小质因数不等于当前数,先输出这个最小质因数,然后将当前数除以该最小质因数,用得到的新值作为参数再次调用递归函数

完整可运行代码

#include <iostream>
using namespace std;

int smallFactor(int);
void printPrimeFactors(int); // 递归函数声明

int main()
{
    int posInt;

    cout << "Enter one positive integer: ";
    cin >> posInt;
    cout << "The prime factors of " << posInt << " are ";

    printPrimeFactors(posInt);
    cout << endl;

    return 0;
}

// 你已实现的最小质因数计算函数
int smallFactor(int posInt)
{
    if (posInt % 2 == 0)
        return 2;

    for (int i = 3; i * i <= posInt; i += 2)
    {
        if (posInt % i == 0)
            return i;
    }

    return posInt;
}

// 新增递归打印所有质因数的函数
void printPrimeFactors(int n) {
    int minPrime = smallFactor(n);
    if (minPrime == n) {
        cout << minPrime;
        return;
    }
    cout << minPrime << " ";
    printPrimeFactors(n / minPrime);
}

测试示例

  • 输入12,输出结果为The prime factors of 12 are 2 2 3
  • 输入7,输出结果为The prime factors of 7 are 7
  • 输入18,输出结果为The prime factors of 18 are 2 3 3

内容的提问来源于stack exchange,提问作者user486543

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 02:09:01