java阶乘算法

来源:互联网 发布:php类与对象做出兔子 编辑:程序博客网 时间:2024/06/10 09:02
//曾经在一家公司面试问的算法题目,现在有时间所以就写一下public static void main(String args[]) {    System.out.println("请输入你的阶乘数:n");    Scanner sc = new Scanner(System.in);    long n = sc.nextInt();    long radix = 0;    while (n != 0) {        radix = Long.MAX_VALUE / n;        radix = (long) Math.pow(10, ("" + radix).length() - 1);        System.out.println("基数为:" + radix + ",结果为:");        long now = System.currentTimeMillis();        javaAlgorithm(n);        System.out.println("第一种时间为:" + (System.currentTimeMillis() - now));        now = System.currentTimeMillis();        showMyAlgorithm(n, radix);        System.out.println("第二种时间为:" + (System.currentTimeMillis() - now));        now = System.currentTimeMillis();        showCAlgorithm(n);        System.out.println("第三种时间为:" + (System.currentTimeMillis() - now));        System.out.println("请继续输入您想要计算的阶乘:n(退出请输入0)");        n = sc.nextInt();    }}//方法3public static void showCAlgorithm(long n) {    int i, digit = 1, j;    long carry, temp;    long[] a = new long[90000001];    a[0] = 1;    for (i = 2; i <= n; i++) {        for (j = 1, carry = 0; j <= digit; j++) {            temp = a[j - 1] * i + carry;            a[j - 1] = temp % 10;            carry = temp / 10;        }        while (carry != 0) {            a[++digit - 1] = carry % 10;            carry = carry / 10;        }    }    System.out.printf("n ! = "); //显示结果    for (j = digit; j >= 1; j--) {        System.out.printf("%d", a[j - 1]);    }    System.out.println();}//方法2public static void showMyAlgorithm(long n, long radix) {    int i, digit = 1, j;    long carry, temp;    long a[] = new long[90000001];    a[0] = 1;    for (i = 2; i <= n; i++) {        for (carry = 0, j = 1; j <= digit; j++) {            temp = a[j - 1] * i + carry;            a[j - 1] = temp % radix;            carry = temp / radix;            if (j == digit) {                if (carry > 0) {                    digit++;                }            }        }    }    System.out.printf("n ! = "); //显示结果    long b = ("" + radix).length() - 1;    for (j = digit; j >= 1; j--) {        if (j == digit) {            System.out.printf("%d", a[j - 1]);            continue;        }        System.out.printf("%0" + b + "d", a[j - 1]);    }    System.out.println();}//方法1public static void javaAlgorithm(long n) {    BigDecimal result = new BigDecimal(1);    for (int i = 1; i <= n; i++) {![这里写图片描述](http://img.blog.csdn.net/20170728193117409?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzQzMDgyOTI=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)        BigDecimal i_value = new BigDecimal(i);        result = result.multiply(i_value);    }    System.out.println("n ! = " + result);}

方法一二三在计算了200000的阶乘后得到的结果是:
这里写图片描述
这里写图片描述
这里写图片描述

第一种方法最快的原因我估计是直接用的位运算而没有用%、/运算。

原创粉丝点击