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的阶乘后得到的结果是:
第一种方法最快的原因我估计是直接用的位运算而没有用%、/运算。
阅读全文
0 0
- java 阶乘 递归算法
- java实现阶乘算法
- java阶乘算法
- Java 实现阶乘算法
- 递归算法 阶乘 JAVA描述
- 递归算法 阶乘 JAVA描述
- 【Java】递归算法计算阶乘
- Java算法 递归算法计算阶乘
- 关于阶乘的四个JAVA算法。
- 关于阶乘的四个JAVA算法
- 阶乘比较快速的算法 递归 Java
- java 素数算法, n的阶乘
- java算法 使用递归计算阶乘
- 阶乘算法
- 算法-->阶乘
- 阶乘算法
- 阶乘算法
- JAVA阶乘
- N皇后
- git本地项目的步骤
- CodeForces
- 正则表达式30分钟入门教程
- iOS开发没有开发者账号照样可以进行真机测试
- java阶乘算法
- 【玖哥乱弹】Android程序员的AI转型之路
- html5预览并上传图片的功能
- 字典树
- html:自定义列表(dl>dt+dd)的使用
- 斯卡布罗集市口琴bd谱
- draw9patch--指定图片的可缩放区域防止失真
- GitLab的IP地址修改
- Permutation Sequence问题及解法