Java Program to find out nCrusing static method.Formula : nCr = n!/((n-r)!*r!)
Objective
Calculate mathematical combinations (nCr) using a static helper method.
Algorithm / Approach
- Define a
static float fact(int x)method that calculates and returns the factorial ofx. - In the
mainmethod, readnandrfrom the user. - Calculate the combination using the formula:
fact(n) / (fact(n-r) * fact(r)). - Print the final result.
Test.java
import java.util.Scanner;
class Test {
public static float fact(int x) {
int f = 1;
for(int i = 1; i<=x; i++) {
f = f*i;
}
return f;
}
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter N: ");
int n = s.nextInt();
System.out.print("Enter R: ");
int r = s.nextInt();
float res=fact(n)/(fact(n-r)*fact(r));
System.out.print("Result = "+res);
}
}
Expected Output
Enter N: 5 Enter R: 3 Result = 10.0
Explanation of the Program
- The
statickeyword allows a method to belong to the class itself, rather than to any specific object instance. - Because
fact()is static, we can call it directly from themainmethod (which is also static) without having to create an object usingnew. - This is highly useful for utility or mathematical functions that don't rely on an object's state (like
Math.pow).
Complexity
Time Complexity
O(n) - Because factorial calculations loop up to n.
Space Complexity
O(1)
Common Mistakes
- Trying to call a non-static method directly from a static context like
main, which results in a compilation error ("non-static method cannot be referenced from a static context").