我制作了该程序来查找数字的素因子,但是当我运行此代码时,它给出的输出错误。我已经调试了此代码,逻辑也正确。 我发现的是,当“ 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++;
}
}
}
答案 0 :(得分:2)
一旦找到第一个除数,就应该退出循环。否则,您的外部方法调用将继续搜索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++;
}
}
答案 1 :(得分:0)
似乎您的意思是下面的递归函数,如下面的演示程序所示:
#include <stdio.h>
void prime( unsigned int x )
{
if ( !( x < 2 ) )
{
unsigned int i = 2;
while ( x % i ) ++i;
printf( "%u, ", i );
prime( x / i );
}
}
int main(void)
{
unsigned int num;
printf( "Enter a number to find its prime factors: " );
scanf( "%u", &num );
printf( "\nPrime factors of %u are: \n", num );
prime( num );
putchar( '\n' );
return 0;
}
程序输出可能类似于:
Enter a number to find its prime factors: 10
Prime factors of 10 are:
2, 5,
该函数的递归调用应放在while循环之外。
答案 2 :(得分:0)
选择递归方法时,关键步骤之一就是确定停止条件。
发布的代码中的问题(或至少一个问题)是在while
循环内 进行递归调用,以便找到并打印主要因素多次。
我也避免每次都从2重新开始因子搜索,但是在那种情况下,您应该向递归函数添加一个参数。在下文中,我将素数分解的逻辑分为两个函数,其中只有一个是递归的。
void prime_impl(int n, int factor, const char* delim)
{
if (n < 2)
return;
while (factor <= n && n % factor)
++factor;
printf("%s%d", delim, factor);
prime_impl(n / factor, factor, " * ");
}
void prime_factorization(int n)
{
printf("%4d", n);
if ( n < 0 )
prime_impl(-n, 2, " = ");
else
prime_impl(n, 2, " = ");
putchar('\n');
}
可测试的here。
答案 3 :(得分:-2)
由于需要上述代码的“调试”,因此我打算以相同的逻辑回答问题。
固定代码:
#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)
{
static int i = 2;
while(x != 1 && i <= x)
{
if(x % i == 0)
{
printf("%d, ", i);
x = x / i;
i++;
prime(x);
break;
}
else
{
i++;
}
}
}