本文介绍了递归FUNC找质因数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我犯了一个递归函数找到一个数的质因子,但它具有使Turbo C的退出的错误。请大家帮忙

 #包括LT&;&stdio.h中GT;
#包括LT&;&CONIO.H GT;
INT素(INT NUM);
INT primefactor(INT NUM,INT I);
无效的主要(无效)
{
    INT NUM;
    的printf(请输入一个数字,其主要因素是计算:);
    scanf函数(%D,试验#);
    primefactor(NUM,I);
     I = NUM
    残培();
}
INT primefactor(INT NUM,int i)以
{
    如果(ⅰ== 2)
    返回1;
    如果(NUM%我== 0)
    {
        如果(素(NUM))
        {
            的printf(%d个,NUM);
            NUM = NUM​​ / I;
            我++;
        }
    }
    一世 - ;
    primefactor(NUM,I);
    返回0;
}
INT素(INT NUM)
{
    INT I,标志;
    对于(i = 2; I<民;我++)
    {
        如果(NUM%我== 0)
    标志= 0;
    }
    返回标志;
}


解决方案

(有点太困了,要写出好的code ..所以很抱歉提前任何错误:P)

一个简单的非递归版本

  printPrimeFactors(INT NUM){  为(ⅰ= 2; I&下; SQRT(NUM); I = getNextPrime()){
     如果(NUM%I)
        的printf(%D,我);
  }}

如果你必须使用递归

  printPrimeFactors(INT NUM){ 如果(isPrime(NUM)){
    的printf(%D,NUM);
 }其他{
    对于(i = 2; I<开方(NUM);我++){
        如果(NUM%我== 0){
              printPrimeFactors(ⅰ);
              printPrimeFactors(NUM / I);
        }
    }
 }}

i made a recursive function to find the prime factors of a number but it has a bug which makes turbo c quit. please help

#include<stdio.h>
#include<conio.h>
int prime(int num);
int primefactor(int num,int i);
void main(void)
{
    int num;
    printf("Enter a number whose prime factors are to be calculated:");
    scanf("%d",&num);
    primefactor(num,i);
     i=num 
    getch();
}
int primefactor(int num,int i)
{
    if(i==2)
    return 1;
    if(num%i==0)
    {
        if(prime(num))
        {
            printf(",%d",num);
            num=num/i;
            i++;
        }


    }
    i--;
    primefactor(num,i);
    return 0;
}
int prime(int num)
{
    int i,flag;
    for(i=2;i<num;i++)
    {
        if(num%i==0)
    flag=0;
    }
    return flag;
}
解决方案

(little too sleepy to write good code.. so am sorry in advance for any bugs :p )

a simpler non recursive version

printPrimeFactors(int num) {

  for (i = 2; i < sqrt(num); i=getNextPrime()) {
     if (num %i)
        printf("%d", i);
  } 

}

if you have to use recursion

printPrimeFactors(int num) {

 if(isPrime(num)) {
    printf ("%d ", num);
 } else {
    for(i=2; i < sqrt(num); i++) {
        if(num%i ==0) {
              printPrimeFactors(i);
              printPrimeFactors(num/i);   
        }
    }
 }

}

这篇关于递归FUNC找质因数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 06:50