KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lsmp > djep > xjep > XMath


1 /* @author rich
2  * Created on 01-Oct-2004
3  *
4  * This code is covered by a Creative Commons
5  * Attribution, Non Commercial, Share Alike license
6  * <a HREF="http://creativecommons.org/licenses/by-nc-sa/1.0">License</a>
7  */

8 package org.lsmp.djep.xjep;
9 import java.util.*;
10 /**
11  * @author Rich Morris
12  * Created on 01-Oct-2004
13  */

14 public class XMath {
15
16     static class LongPair {
17         long a,b;
18         public LongPair(long x,long y) { a=x; b=y;}
19         long x() { return a; }
20         long y() { return b; }
21         public boolean equals(Object JavaDoc o) {
22             if(!( o instanceof LongPair)) return false;
23             LongPair p = (LongPair) o;
24             return (a == p.a) && (b == p.b);
25         }
26
27         public int hashCode() {
28             int result = 17;
29             int xi = (int)(a^(a>>32));
30             int yi = (int)(b^(b>>32));
31             result = 37*result+xi;
32             result = 37*result+yi;
33             return result;
34         }
35         public String JavaDoc toString() { return "("+a+","+b+")"; }
36         
37     }
38     static Hashtable pascal = new Hashtable();
39
40     public static long binomial(long n,long i)
41     {
42         if(i==0 || n==i) return 1;
43         if(i==1 || n==i-1 ) return n;
44         return binomial(new LongPair(n,i));
45     }
46     
47     public static long binomial(LongPair pair)
48     {
49         Object JavaDoc find = pascal.get(pair);
50         if(find == null)
51         {
52             long l = binomial(pair.x()-1,pair.y()-1);
53             long r = binomial(pair.x()-1,pair.y());
54             pascal.put(pair,new Long JavaDoc(l+r));
55             return l+r;
56         }
57         else return ((Long JavaDoc) find).longValue();
58     }
59 }
60
Popular Tags