如何改写递归因式分解函数实现逆序输出?输入105因子缺失求助
问题:递归因数分解函数逆序输出异常
我需要改写递归函数,使其输出因数分解的逆序结果:输入-105时,期望输出(7 5 3),但当前代码输出(3 5 7)。我对函数做小幅修改后实现了逆序,但输入105时程序仅输出(7 5),缺失第三个数字。相关代码如下:
初始代码
#include <stdio.h> void simpleFactors(unsigned int a, unsigned int last, unsigned int n); void printFactor(unsigned int last, unsigned int n); int main() { unsigned int a; scanf("%u", &a); simpleFactors(a, 2, 0); printf("\n"); return 0; } void simpleFactors(unsigned int a, unsigned int last, unsigned int n) { if (a % last == 0) { if (a > 1) simpleFactors(a / last, last, n + 1); } else { printFactor(last, n); if (a == 1) return; if (last * last > a) { printf("%ld ", a); return; } simpleFactors(a, last + 1, 0); printf("\n"); } } void printFactor(unsigned int last, unsigned int n) { if (n == 0) return; if (n == 1) printf("%ld ", last); else printf("%ld^%ld ", last, n); }
修改后的代码
void simpleFactors(unsigned int a, unsigned int last, unsigned int n) { if (a % last == 0) { if (a > 1) simpleFactors(a / last, last, n+1); } else { if (last > a) { printFactor(last, n); } if (a == 1) return; if (last * last > a) { printf("%ld ", a); printFactor(last, n); return; } simpleFactors(a, last + 1, 0); printf("\n"); } }
解决方案
问题分析
- 原始代码递归逻辑是先处理小因数再打印,输出顺序从小到大;要逆序需先处理大因数再回溯打印小因数。
- 修改后的代码添加了错误的
last > a判断,导致最后一个质数因数无法触发打印逻辑,输入105时缺失数字3。 - 原代码用
unsigned int接收负数会导致值异常,输入-105实际处理的是无符号大整数,不符合需求。
修复后代码
核心思路是先递归处理更大的因数,再回溯打印当前因数,同时补全边界处理:
#include <stdio.h> void simpleFactors(unsigned int a, unsigned int last, unsigned int n); void printFactor(unsigned int last, unsigned int n); int main() { // 处理负数输入:先转绝对值 int temp; scanf("%d", &temp); unsigned int a = temp < 0 ? -temp : temp; simpleFactors(a, 2, 0); printf("\n"); return 0; } void simpleFactors(unsigned int a, unsigned int last, unsigned int n) { if (a % last == 0) { if (a > 1) simpleFactors(a / last, last, n + 1); // 递归到a=1时,打印当前因数的统计结果 if (a == 1) printFactor(last, n + 1); } else { // 先打印之前统计的因数(如果有) printFactor(last, n); if (a == 1) return; // 当前last平方大于a时,a本身是质数,直接打印 if (last * last > a) { printf("%u ", a); return; } // 先递归处理更大的因数,再回溯打印,实现逆序 simpleFactors(a, last + 1, 0); } } void printFactor(unsigned int last, unsigned int n) { if (n == 0) return; if (n == 1) printf("%u ", last); else printf("%u^%u ", last, n); }
修复说明
- 负数输入处理:先通过
int接收输入,转成绝对值后再用unsigned int处理,确保-105实际处理的是105。 - 逆序逻辑实现:调整递归顺序,先深入处理更大的因数,再回溯打印当前因数,自然实现从大到小的输出。
- 缺失数字修复:在
a%last==0分支中,当a==1时主动调用printFactor,确保最后一个因数被打印;移除错误的last > a判断。 - 类型匹配修正:把
printf中的%ld改成%u,匹配unsigned int类型,避免类型不匹配警告。
测试验证:
- 输入
105,输出7 5 3 - 输入
-105,输出7 5 3
内容的提问来源于stack exchange,提问作者Евгений Смирнов
相关产品推荐
相关产品推荐

