Java Program to calculate nCr and 1!+2!+3!+4! using inheritance. FORMULA: nCr = n!/(r!*(n-r)!)
Objective
Write a Java program to demonstrate Hierarchical Inheritance by calculating both nCr and a factorial series.
Algorithm / Approach
- Create a base class
Factorialwith a methodfact(x)to calculate factorials. - Create a class
SeriesAthatextends Factorialto calculate nCr using the inheritedfact()method. - Create another class
SeriesBthat alsoextends Factorialto calculate the sum of factorials. - In
main, instantiate both child classes independently and execute their respective calculations.
Factorial.java
import java.util.Scanner;
class Factorial {
Scanner s=new Scanner(System.in);
int fact(int x) {
int res = 1;
for(int i=1; i<= x; i++) {
res = res * i;
}
return res;
}
}
class SeriesA extends Factorial{
public void calculate() {
System.out.print("Enter N: ");
int n = s.nextInt();
System.out.print("Enter R: ");
int r = s.nextInt();
int res=fact(n)/(fact(n-r)*fact(r));
System.out.println("Result- "+res);
}
}
class SeriesB extends Factorial {
public void show() {
System.out.print("Enter N: ");
int n = s.nextInt();
int sum =0;
for(int i=1; i<=n; i++) {
sum = sum+fact(i);
}
System.out.print("Result- "+sum);
}
}
class Main{
public static void main(String[] a)
{
SeriesA s = new SeriesA();
s.calculate();
SeriesB s2 = new SeriesB();
s2.show();
}
}
Expected Output
Enter N: 5 Enter R: 3 Result- 10 Enter N: 5 Result- 153
Explanation of the Program
- Hierarchical inheritance occurs when multiple derived classes inherit from a single base class.
- In this program, calculating both nCr and factorial sums requires repeatedly calculating factorials. Instead of writing the factorial logic twice, we place it in a common parent class.
- Both
SeriesAandSeriesBcan now share this utility method without repeating code.
Complexity
Time Complexity
O(n) - Dominated by the factorial loops.
Space Complexity
O(1)