關於階乘的四個JAVA算法

關於階乘的四個JAVA算法。
這裏有四個關於計算階乘的,難度依次提升,全部通過測試。
這應該是基本代碼了,與之共勉。

這是利用簡單的循環相乘製造的階乘。
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));
    }
}

這個是利用遞歸算法制成的。

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

這個是數組添加的方法制成的,可以計算更大的階乘。

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 be non-negative.");
        } while (last < x) {
            table[last + 1] = table[last] * (last + 1);
            last++;
        }
        return table[x];
    }
        public static void main(String[] args) {

最後一個是利用BigInteger類製成的,這裏可以用更大的更大的階乘。

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

            System.out.print(factorial(20));
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章