Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* In combinatorics, the Catalan numbers are calculated by the following formula:
- * C = (2n)! / ((n + 1)! * n!)
- * Write a program to calculate the nth Catalan number by given n (1 < n < 100). */
- import java.math.BigDecimal;
- import java.math.BigInteger;
- import java.util.Scanner;
- public class CatalanNums {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scanner = new Scanner(System.in);
- System.out.print("Enter a whole positive number in the range [2 .. 99] for N: ");
- int numN = scanner.nextInt();
- scanner.close();
- if (numN > 1 && numN < 100) {
- BigDecimal catalanNumber = BigDecimal.ONE;
- for (int i = numN; i > 1; i--) {
- BigDecimal quotient = new BigDecimal("" + (i + numN));
- quotient = quotient.divide(new BigDecimal("" + i), 50, BigDecimal.ROUND_HALF_UP);
- catalanNumber = catalanNumber.multiply(quotient);
- }
- BigInteger result = catalanNumber.setScale(0, BigDecimal.ROUND_HALF_UP).toBigInteger();
- System.out.printf("The %d-th Catalan number is equal to: %s !\n",
- numN, result);
- } else {
- System.out.println("Error! - Invalid Input number!!!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement