Advertisement
dimipan80

Catalan Numbers

Aug 8th, 2014
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. /* In combinatorics, the Catalan numbers are calculated by the following formula:
  2.  * C = (2n)! / ((n + 1)! * n!)
  3.  * Write a program to calculate the nth Catalan number by given n (1 < n < 100). */
  4.  
  5. import java.math.BigDecimal;
  6. import java.math.BigInteger;
  7. import java.util.Scanner;
  8.  
  9. public class CatalanNums {
  10.  
  11.     public static void main(String[] args) {
  12.         // TODO Auto-generated method stub
  13.         Scanner scanner = new Scanner(System.in);
  14.         System.out.print("Enter a whole positive number in the range [2 .. 99] for N: ");
  15.         int numN = scanner.nextInt();
  16.         scanner.close();
  17.  
  18.         if (numN > 1 && numN < 100) {
  19.             BigDecimal catalanNumber = BigDecimal.ONE;
  20.             for (int i = numN; i > 1; i--) {
  21.                     BigDecimal quotient = new BigDecimal("" + (i + numN));
  22.                     quotient = quotient.divide(new BigDecimal("" + i), 50, BigDecimal.ROUND_HALF_UP);
  23.                     catalanNumber = catalanNumber.multiply(quotient);
  24.             }
  25.  
  26.             BigInteger result = catalanNumber.setScale(0, BigDecimal.ROUND_HALF_UP).toBigInteger();
  27.             System.out.printf("The %d-th Catalan number is equal to: %s !\n",
  28.                             numN, result);
  29.     } else {
  30.             System.out.println("Error! - Invalid Input number!!!");
  31.         }
  32.     }
  33.  
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement