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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值