Factorial Program in C, C++ and Java: 4 Methods
Find the factorial of a number in C, C++ and Java using iterative, recursive, tgamma, and BigInteger methods, with working code and a side-by-side comparison.
Factorial shows up in three places every placement candidate encounters: permutation and combination problems, recursion design questions, and the write-a-function warm-up that opens campus coding rounds in C, C++, or Java.
This guide covers the four standard approaches across all three languages, with working code and explanation of when each method fits.
What Factorial Means
The factorial of a non-negative integer n is the product of all positive integers from 1 to n. Two boundary cases matter for correct implementations.
- n = 0: The factorial of 0 equals 1 by convention (the empty product). Programs that return 0 here are wrong.
- Negative n: Factorial is undefined for negative integers. A robust program returns -1 or throws an exception rather than computing a meaningless result.
Quick reference values:
| n | n factorial |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 3 | 6 |
| 5 | 120 |
| 10 | 3,628,800 |
| 20 | 2,432,902,008,176,640,000 |
In combinatorics, factorial is everywhere. The number of ways to arrange n distinct objects is n factorial. The combinations formula nCr = n factorial divided by (r factorial × (n minus r) factorial) appears in the probability sections of every placement aptitude test.
Placement tests in C, C++, or Java commonly ask for implementations across all four methods below. Read the problem statement carefully: “without recursion” means iterative only; “without loops” typically means recursion or tgamma.
Factorial Program in C
Method 1: Iterative (for loop)
The iterative approach is the safest for general use. Declare the return type as long long, not int. A plain int overflows at n = 13, so use long long for any factorial computation in C.
#include <stdio.h>
long long factorial(int n) {
if (n < 0) return -1;
long long result = 1;
int i;
for (i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
int main() {
printf("Factorial of 5 = %lld\n", factorial(5));
printf("Factorial of 0 = %lld\n", factorial(0));
return 0;
}
Output:
Factorial of 5 = 120
Factorial of 0 = 1
The negative-n guard (if (n < 0) return -1) is a detail interviewers check. A solution without it is incomplete. The for-loop pattern here is the same traversal structure used in finding the smallest and largest element in an array: iterate across a range, accumulate a result.
Method 2: Recursive
#include <stdio.h>
long long factorial(int n) {
if (n < 0) return -1;
if (n == 0 || n == 1) return 1;
return n * factorial(n - 1);
}
int main() {
printf("Factorial of 5 = %lld\n", factorial(5));
return 0;
}
The base case covers both n = 0 and n = 1. Each recursive call reduces n by 1 until it reaches the base. Stack depth equals n, which is fine for interview-sized inputs (n = 10 to 20) but will overflow the call stack for very large n.
Method 3: Using tgamma (math.h)
The gamma function satisfies this identity: tgamma(n+1) equals n factorial for positive integers. This lets you compute factorial with a single function call and no loop.
#include <stdio.h>
#include <math.h>
int main() {
int n = 5;
printf("Factorial of %d = %.0f\n", n, tgamma(n + 1));
return 0;
}
Compile with the -lm flag to link the math library: gcc factorial.c -lm -o factorial.
The C standard library tgamma reference at cppreference.com notes that tgamma returns a double. Floating-point precision means results above n = 20 may not be exact integers. Avoid tgamma when you need an exact integer count for combinatorics or probability problems.
Factorial Program in C++
C++ factorial is structurally identical to C. The differences are <iostream> instead of <stdio.h>, and cout instead of printf. The data type constraints are the same: long long handles n up to 20.
Iterative in C++
#include <iostream>
using namespace std;
long long factorial(int n) {
if (n < 0) return -1;
long long result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
int main() {
cout << "Factorial of 5 = " << factorial(5) << endl;
cout << "Factorial of 0 = " << factorial(0) << endl;
return 0;
}
Recursive in C++
#include <iostream>
using namespace std;
long long factorial(int n) {
if (n < 0) return -1;
if (n == 0 || n == 1) return 1;
return n * factorial(n - 1);
}
int main() {
cout << "Factorial of 5 = " << factorial(5) << endl;
return 0;
}
Recursive string problems follow the same base-case structure. If you’re working on palindrome checking in C or Java, you’ll see the pattern again: define when to stop, reduce the problem by one step, combine results.
C++ also has std::tgamma in <cmath> if you need the gamma-function approach. The same precision limitation applies as in C.
Factorial Program in Java
Java’s long type handles n up to 20 for factorial. Beyond n = 20, the value overflows a 64-bit long. For n above 20, java.math.BigInteger handles arbitrarily large integers cleanly.
Iterative in Java
public class Factorial {
public static long factorial(int n) {
if (n < 0) return -1;
long result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
public static void main(String[] args) {
System.out.println("Factorial of 5 = " + factorial(5));
System.out.println("Factorial of 0 = " + factorial(0));
}
}
Recursive in Java
public class Factorial {
public static long factorial(int n) {
if (n < 0) return -1;
if (n == 0 || n == 1) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println("Factorial of 5 = " + factorial(5));
}
}
Large n: BigInteger
For competitive programming problems or interview questions where n can be 50 or 100, switch to java.math.BigInteger. The Java 8 BigInteger API documentation covers the full set of arithmetic methods.
import java.math.BigInteger;
public class Factorial {
public static BigInteger factorial(int n) {
if (n < 0) throw new IllegalArgumentException("n must be non-negative");
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
public static void main(String[] args) {
System.out.println("Factorial of 20 = " + factorial(20));
System.out.println("Factorial of 25 = " + factorial(25));
}
}
Output:
Factorial of 20 = 2432902008176640000
Factorial of 25 = 15511210043330985984000000
BigInteger.ONE initialises the accumulator to 1. The multiply method handles arbitrarily wide integers, with no overflow and no floating-point approximation.
Comparing the Four Approaches
All iterative and recursive variants run in O(n) time. The BigInteger iterative approach also runs O(n) iterations, though each multiplication is slower because operand size grows as n increases.
| Method | Language | Exact results up to n | Space | Best for |
|---|---|---|---|---|
| Iterative | C, C++ | 20 (long long) | O(1) | General use |
| Recursive | C, C++ | 20 (long long) | O(n) | Clean code demos |
| tgamma | C, C++ | ~20 (approx only) | O(1) | Quick estimates |
| Iterative | Java | 20 (long) | O(1) | General use |
| Recursive | Java | 20 (long) | O(n) | Clean code demos |
| BigInteger | Java | Unlimited | O(digits) | n above 20 |
Choose iterative when you need reliability across arbitrary n. Choose recursive when the interviewer specifically wants to see your base-case and recursive-call structure. Choose BigInteger in Java when the problem states n can be large.
A Common Interview Follow-up: Trailing Zeros
After you implement factorial, interviewers often ask: how many trailing zeros does the factorial of n have? This question does not require computing factorial at all.
A trailing zero comes from multiplying 10, which factors as 2 × 5. Since every even number contributes at least one factor of 2, there are always more 2s than 5s in the prime factorisation of n factorial. So the count of trailing zeros equals the count of 5s in the factorisation, which is the count of multiples of 5, plus multiples of 25 (which contribute two 5s each), plus multiples of 125, and so on.
Formula: trailing zeros = floor(n/5) + floor(n/25) + floor(n/125) + …
Worked examples:
- For n = 10: floor(10/5) = 2 trailing zeros
- For n = 25: floor(25/5) + floor(25/25) = 5 + 1 = 6 trailing zeros
- For n = 100: floor(100/5) + floor(100/25) = 20 + 4 = 24 trailing zeros
This shows up across placement tests and coding rounds. The FACE Prep data structures interview question guide covers related DSA patterns worth reviewing alongside factorial.
The iterative loop that computes trailing zeros, dividing n by successive powers of 5, is the same design pattern that appears when building tools on top of LLMs: iterate over inputs, process each step, accumulate results. TinkerLLM is where you apply that same algorithmic thinking to real LLM API calls, for ₹299. The resulting project, where you make deliberate choices about how to structure inputs and handle edge cases, is what you show a recruiter when they ask what you’ve actually built.
Primary sources
Frequently asked questions
What is the factorial of 0?
The factorial of 0 equals 1 by convention. This is the empty product. Every correct factorial implementation must return 1 for n = 0, not 0.
Can int store the factorial of 20 in C?
No. A 32-bit signed int holds up to 2,147,483,647. The factorial of 13 equals 6,227,020,800, which already exceeds that. Use long long, which handles n up to 20.
What is the largest n that fits in a long long factorial in C?
The factorial of 20 fits in a long long. The factorial of 21 overflows a 64-bit signed long long. For n above 20 in Java, switch to BigInteger.
Why does factorial by recursion fail for very large n?
Each recursive call adds a frame to the call stack. For n above a few thousand, the stack overflows. Use the iterative method when n is large.
Is the factorial of a negative number defined?
No. Factorial is defined only for non-negative integers. Add a guard clause that returns -1 or throws an exception for negative input.
Does Java have a built-in factorial method?
No built-in method exists in the Java standard library. Write your own loop or recursive function. For n above 20, use java.math.BigInteger to avoid overflow.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)