Advertisement
calcpage

CH18_NewMath.java

Apr 27th, 2012
393
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.37 KB | None | 0 0
  1. public class NewMath
  2. {
  3.     //iterative pow() method!
  4.     public static int pow(int base, int exp)
  5.     {
  6.         int prod = 1;
  7.         for(int i=0; i<exp; i++)
  8.         {
  9.             prod*=base;
  10.         }
  11.         return prod;
  12.     }
  13.  
  14.     //how the Math class does pow()!!
  15.     public static double pow(double base, double exp)
  16.     {
  17.         return Math.exp(exp*Math.log(base));
  18.     }
  19.  
  20.     //recursive pow() method!!!
  21.     public static double pow(double base, int exp)
  22.     {
  23.         if(exp==0)
  24.         {
  25.             return 1;
  26.         }
  27.         return base*pow(base,exp-1);
  28.     }
  29.  
  30.     //another recursive method, now for factorials
  31.     public static int fact(int num)
  32.     {
  33.         if(num==0)
  34.         {
  35.             return 1;
  36.         }
  37.         return num*fact(num-1);
  38.     }
  39.  
  40.     //recursing in public! evaluate nCr
  41.     public static int pascal(int row, int col)
  42.     {
  43.         if(col==0 || row==col)
  44.         {
  45.             return 1;
  46.         }
  47.         return pascal(row-1,col)+pascal(row-1,col-1);
  48.     }
  49.  
  50.     //recursing in public! find one row of pascal's triangle
  51.     public static String pascalRow(int n)
  52.     {
  53.         String temp = "";
  54.         for(int i=0; i<=n; i++)
  55.         {
  56.             temp += pascal(n,i) + "\t";        
  57.         }
  58.         return temp;
  59.     }
  60.  
  61.     //recursing in public! print out pascal's triangle
  62.     public static String pascalTri(int n)
  63.     {
  64.         String temp = "";
  65.         for(int i=0; i<=n; i++)
  66.         {
  67.             temp += pascalRow(i) + "\n";
  68.         }
  69.         return temp;
  70.     }
  71.  
  72.     //find fibonacci sequence terms
  73.     public static int fib(int n)
  74.     {
  75.         if(n==0 || n==1){return 1;}
  76.         return fib(n-1)+fib(n-2);
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement