gpt4 book ai didi

c - 为什么它显示主要因子的输出错误?

转载 作者:行者123 更新时间:2023-11-30 19:25:24 25 4
gpt4 key购买 nike

我编写这个程序是为了查找数字的质因数,但是当我运行此代码时,它给出了错误的输出。我已经调试了这段代码,逻辑也是正确的。我发现,当“x == 1”时,程序会出现错误。我找不到答案。

#include<stdio.h>
void prime(int );
main()
{
int num;

printf("Enter a number to find its prime factors: ");
scanf("%d", &num);

printf("\nPrime factors of %d are: \n", num);

prime(num);
}

void prime(int x)
{
int i = 2;

while(x != 1)
{
if(x % i == 0)
{
printf("%d, ", i);

x = x / i;
prime(x);
}

else
{
i++;
}

}
}

最佳答案

一旦找到第一个除数,就应该中断循环。否则,您的外部方法调用将继续搜索 x 的除数,即使不再需要它:

void prime(int x) {
if (x == 0) {
printf("All prime numbers are prime factors of 0");
return;
}

if (x == INT_MIN) {
printf("Please provide a number larger than %i", INT_MIN);
return;
}

x = abs(x);
int i = 2;
while(x != 1) {
if(x % i == 0) {
printf("%d, ", i);

x = x / i;
prime(x);
break; // break here
}
i++;
}
}

更新

但是,这里实际上并不需要递归 - 相反,您可以使用如下简单的迭代算法:

void prime(int x) {
if (x == 0) {
printf("All prime numbers are prime factors of 0");
return;
}

if (x == INT_MIN) {
printf("Please provide a number larger than %i", INT_MIN);
return;
}

x = abs(x);
int i = 2;
while (x != 1) {
if (x % i == 0) {
printf("%d, ", i);
x = x / i;
}
i++;
}
}

关于c - 为什么它显示主要因子的输出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58891079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com