Take the 2-minute tour ×

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>

int rfact(int n);

    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


    //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);
    return temp;
share|improve this question

3 Answers 3

up vote 5 down vote accepted

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 :)

share|improve this answer

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

share|improve this answer

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

share|improve this answer
oh wow big facepalm there thats a good point –  speedofdark8 Feb 25 '13 at 1:19

Your Answer


