Factorial Three Ways
C
Easy
4 views
Problem Description
Calculate factorials using three methods: root-recursive, recursive, and tail-recursive. Examine the efficiency of each method for large numbers.
Official Solution
#include <stdio.h>
long long fact_recursive(int n) {
if (n == 0) return 1;
return n * fact_recursive(n - 1);
}
long long fact_tail(int n, long long result) {
if (n == 0) return result;
return fact_tail(n - 1, result * n);
}
long long fact_root(int start, int end) {
if (start > end) return 1;
if (start == end) return start;
int mid = (start + end) / 2;
return fact_root(start, mid) * fact_root(mid + 1, end);
}
int main() {
int n = 10;
printf("Recursive: %lldn", fact_recursive(n));
printf("Tail Recursive: %lldn", fact_tail(n, 1));
printf("Root Recursive: %lldn", fact_root(1, n));
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!