Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to calculate nCr and 1!+2!+3!+4! using abstract class. FORMULA: nCr = n!/(r!*(n-r)!).

Java Code Example — Abstract and Interface Programs

ADVERTISEMENT

Java Program to calculate nCr and 1!+2!+3!+4! using abstract class. FORMULA: nCr = n!/(r!*(n-r)!).

Objective

Write a Java program to calculate nCr and factorial sums using an abstract class.

Algorithm / Approach

  1. Create an abstract class Factorial with a concrete method fact() that calculates the factorial of a number.
  2. Add an abstract method calculate() to force subclasses to define their specific calculation logic.
  3. Create PatternA to extend Factorial and implement calculate() for the nCr formula.
  4. Create PatternB to extend Factorial and implement calculate() for summing a series of factorials.
  5. Instantiate both subclasses in main and execute them.
Factorial.java
import java.util.Scanner;
abstract class Factorial {
 Scanner s=new Scanner(System.in);
 abstract void calculate();
 int fact(int x) {
  int res = 1;
  for(int i=1; i<= x; i++) {
   res = res * i;
  }
 return res;
 }
}
class PatternA 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 PatternB extends Factorial {
 public void calculate() {
  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)
 {
  PatternA p = new PatternA();
  p.calculate();
  PatternB p2 = new PatternB();
  p2.calculate();
 }
}

Expected Output

Enter N: 5
Enter R: 2
Result- 10
Enter N: 6
Result- 873

Explanation of the Program

  • This program is very similar to the hierarchical inheritance example, but it uses abstraction to enforce rules.
  • By declaring calculate() as abstract in the parent class, the compiler ensures that any developer who creates a new subclass of Factorial MUST provide a calculate() method.
  • This prevents human error and guarantees a consistent API across all related classes.

Complexity

Time Complexity O(n) - Dominated by the factorial loops.
Space Complexity O(1)
ADVERTISEMENT