PascalsTriangle.java

Go to the documentation of this file.
00001 package com.graphbuilder.math;
00002 
00006 public final class PascalsTriangle {
00007 
00008     private PascalsTriangle() {};
00009 
00010     private static double[][] pt = new double[][] { {1} };
00011 
00023     public synchronized static double nCr(int n, int r) {
00024         if (n < 0 || r < 0 || r > n) return 0;
00025 
00026         if (n >= pt.length) {
00027             int d = 2 * pt.length;
00028             double[][] pt2 = null;
00029             if (n > d)
00030                 pt2 = new double[n + 1][];
00031             else
00032                 pt2 = new double[d + 1][];
00033 
00034             for (int i = 0; i < pt.length; i++)
00035                 pt2[i] = pt[i];
00036 
00037             for (int i = pt.length; i < pt2.length; i++) {
00038                 pt2[i] = new double[(i / 2) + 1];
00039 
00040                 pt2[i][0] = 1;
00041 
00042                 for (int j = 1; j < pt2[i].length; j++) {
00043                     double x = pt2[i-1][j-1];
00044                     if (j < pt2[i-1].length)
00045                         x = x + pt2[i-1][j];
00046                     else
00047                         x = 2 * x;
00048 
00049                     pt2[i][j] = x;
00050                 }
00051             }
00052             pt = pt2;
00053         }
00054 
00055         if (2 * r > n)
00056             r = n - r;
00057 
00058         return pt[n][r];
00059     }
00060 
00064     public synchronized static void reset() {
00065         pt = new double[][] { {1} };
00066     }
00067 }

Generated on 5 May 2015 for HPCVIEWER by  doxygen 1.6.1