Recursive factorial program in C hangs when executing

倖福魔咒の 提交于 2019-12-11 06:46:15

问题


I'm writing a program to display the time needed to calculate a factorial of a given number 2 million times. I'm writing it using Debian Linux in the C/C++ Eclipse environment. When the program gets to int temp = n * rfact(n-1);, it hangs and won't do anything else.

Here's what I've got so far:

#include <stdio.h>
#include <time.h>

//prototypes
int rfact(int n);

main()
{
    int n = 0;
    int i = 0;
    double result = 0.0;
    clock_t t;
    printf("Enter a value for n: ");
    scanf("%i", &n);

printf("n=%i\n", n);

    //get current time
    t = clock();

    //process factorial 2 million times
    for(i=0; i<2000000; i++)
    {
        rfact(n);
    }

    printf("n=%i\n", n);

    //get total time spent in the loop
    result = (clock() - t)/(double)CLOCKS_PER_SEC;

    //print result
    printf("runtime=%d\n", result);
}

//factorial calculation
int rfact(int n)
{
    int temp = n * rfact(n-1);
    printf(i++);
    return temp;
}

回答1:


You are missing the base case, so you are running into an infinite recursion. You need to stop when you get to n == 1 or n == 0:

int rfact(int n)
{
    if (n <= 0)
        return 1;
    return n * rfact(n-1);
}

Also, the factorial function is not really the best use case for recursion because the iterative version is arguably more readable and possibly a lot faster, but that's a different story :)




回答2:


There is no base case in your rfact function. This means that the rfact(n-1) will be called forever.




回答3:


I agree with people above me, you are missing the base case of recursion

But be aware of doing a factorial 2'000'000 times, your variable will go overflow apart from taking a lot of time for the computation to be terminated



来源:https://stackoverflow.com/questions/15058449/recursive-factorial-program-in-c-hangs-when-executing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!