DEV Community

Discussion on: Head recursion Vs Tail recursion

Collapse
 
imthedarkclown profile image
Shri Arun • Edited

@soorya54 Does return n*getFactorial(n-1); make it a head recursion?
Loved it.

Collapse
 
soorya54 profile image
soorya54

Yes, @imthedarkclown . A better optimization for this will be

int getFactorial(int n, int num) {
    if(n==0)
        return num;
    return getFactorial(n-1, n*num);
}

int main() {
    int n, res;
    scanf("%d", &n);

    res = getFactorial(n,1);
    printf("%d", res);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode