Four example code for Java computing factorial

Source: Internet
Author: User
Tags int size

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));
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.