zoukankan      html  css  js  c++  java
  • Java 实现阶乘算法

    阶乘算法如下:
    以下列出 0 至 20 的阶乘:
    0!=1,(0 的阶乘是存在的)
    1!=1,
    2!=2,
    3!=6,
    4!=24,
    5!=120,
    6!=720,
    7!=5040,
    8!=40320
    9!=362880
    10!=3628800
    11!=39916800
    12!=479001600
    13!=6227020800
    14!=87178291200
    15!=1307674368000
    16!=20922789888000
    17!=355687428096000
    18!=6402373705728000
    19!=121645100408832000
    20!=2432902008176640000
    而当 n≥5 时,n!的个位数字都是0。
    package com.leo.kang.interview;
    
    import java.math.BigDecimal;
    
    public class Factorial {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		System.out.println("--------递归算法-------");
    		System.out.println(factorialRecursive(20));
    
    		System.out.println("--------循环算法-------");
    		System.out.println(factorialLoop(25));
    		
    		System.out.println("--------BigDecimal算法-------");
    		System.out.println(factorial(new BigDecimal(100)));
    	}
    
    	/**
    	 * 递归实现阶乘算法
    	 * 
    	 * @param n
    	 * @return
    	 */
    	public static long factorialRecursive(int n) {
    		// 阶乘对整数才有意义
    		if (n < 0) {
    			return -1;
    		}
    
    		// 0!=1,(0 的阶乘是存在的)
    		if (n == 0) {
    			return 1;
    		}
    
    		if (n < 2)
    			return n * 1;
    		return n * factorialRecursive(n - 1);
    	}
    
    	/**
    	 * 循环实现阶乘算法
    	 * @param n
    	 * @return
    	 */
    	public static long factorialLoop(int n) {
    		// 阶乘对整数才有意义
    		if (n < 0) {
    			return -1;
    		}
    
    		// 0!=1,(0 的阶乘是存在的)
    		if (n == 0) {
    			return 1;
    		}
    
    		// 初始值必须为1才有意义
    		long result = 1;
    		for (int i = n; i > 0; i--) {
    			result *= i;
    		}
    
    		return result;
    	}
    	
    	public static BigDecimal factorial(BigDecimal n){  
            BigDecimal bd1 = new BigDecimal(1);//BigDecimal类型的1  
            BigDecimal bd2 = new BigDecimal(2);//BigDecimal类型的2</span><span>  
            BigDecimal result = bd1;//结果集,初值取1  
            while(n.compareTo(bd1) > 0){//参数大于1,进入循环  
                result = result.multiply(n.multiply(n.subtract(bd1)));//实现result*(n*(n-1))  
                n = n.subtract(bd2);//n-2后继续  
            }  
            return result;  
        } 
    
    }
    

      

  • 相关阅读:
    [CSS] prefers-reduced-motion
    [VSCode] Adding Custom Syntax Highlighting to a Theme in VSCode
    Subversion/Git/ReviewBoard工作流程
    oracle hints
    Node.js学习(10)----文件系统fs
    网络子系统41_inet_peer平衡二叉树的删除
    由链表初始化看C语言的二级指针
    挣值管理不是搞数字游戏(4)——让挣值管理实用!
    关于数据库一致改关闭下redo日志文件丢失的处理办法的总结
    Android 操作系统的内存回收机制
  • 原文地址:https://www.cnblogs.com/kangyi/p/4263161.html
Copyright © 2011-2022 走看看