public class Factorial {
public static int factorial (int x) {
if (x < 0) {
throw new IllegalArgumentException ("x must be>=0");
}
int fact = 1;
for (int i = 2; i <= x; i++) {
Fact *= I;
}
return fact;
}
public static void Main (String args[]) {
System.out.print (factorial (10));
}
}
This is made using recursive algorithms.
public class Factorial2 { public static int Factorial2 (int x) { if (x < 0) { throw new IllegalArgumentException ("x must be>=0"); } if (x <= 1) { return 1; } else return x * FACTORIAL2 (X-1); } public static void Main (String args[]) { System.out.print (Factorial2 (10)); } } |
This is made from the method of array addition, which can compute the larger factorial.
public class factorial3 { static long[] table = new long[21]; static {table[0] = 1; } static int last = 0; Public static long factorial (int x) throws illegalargumentexception { if (x >= table.length) { throw new illegalargumentexception ("Overflow; x is too large. "); } if (x <= 0) { throw new illegalargumentexception ("X must&nbs P;be non-negative. "); } while (last < x) { table[last + 1] = table[last] * (last + 1); last++; } return table[x]; } Public static void main (String[] args) { System.out.print (factorial (17)); } } |
The last one is made from the BigInteger class, where a larger, larger factorial can be used.
Import Java.math.BigInteger; Import java.util.*; public class factorial4{ protected static ArrayList table = new ArrayList (); static{Table.add (biginteger.valueof (1));} public static synchronized BigInteger factorial (int x) { for (int size=table.size (); size<=x;size++) { BigInteger lastfact= (BigInteger) table.get (size-1); BigInteger nextfact= lastfact.multiply (biginteger.valueof (size)); Table.add (nextfact); } Return (BigInteger) table.get (x); } public static void Main (string[] args) { System.out.print (factorial (17)); } } |