递归 -- 阶乘

 n! = n * (n-1) * (n-2) * (n-3) * ... * 1

 

阶乘指从1乘以2乘以3乘以4一直乘到所要求的数。例如所要求的数是4,则阶乘式是1×2×3×4,得到的积是24,24就是4的阶乘。 例如所要求的数是6,则阶乘式是1×2×3×……×6,得到的积是720,720就是6的阶乘。例如所要求的数是n,则阶乘式是1×2×3×……×n,设得到的积是x,x就是n的阶乘。 任何大于1的自然数n阶乘表示方法: n!=1×2×3×……×n  或 n!=n×(n-1)!  5!=5*4*3*2*1=120( n的双阶乘:  当n为奇数时表示不大于n的所有奇数的乘积  如:7!!=1×3×5×7   当n为偶数时表示不大于n的所有偶数的乘积(除0外)   如:8!!=2×4×6×8   小于0的整数-n的阶乘表示(-n)!= 1 / (n+1)!)

 

 

Common.java

package com.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Common {
	
	public static String getString() throws IOException {

		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		return br.readLine();
	}

	public static int getInt() throws IOException {
		String in = getString();
		return Integer.parseInt(in);
	}
}



FactorialApp.java

package com.ch6.triangle;

import java.io.IOException;

import com.util.Common;

public class FactorialApp {

	public static int factorial(int n) {
		if (n == 0) {
			System.out.println("Returned 1 .") ;
			return 1;
		} else {
			int temp = n * factorial(n -1) ;
			System.out.println("Returning : " + temp ) ;
			return temp;
		}
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		while (true) {
			System.out.println("Enter a number: ");
			int n = Common.getInt();

			int ret = factorial(n);
			System.out.println("factorial("+ n + ") is Returned : " + ret);
			System.out.println(" ");
		}
	}

}

 

输出结果:

Enter a number:
6
Returned 1 .
Returning : 1
Returning : 2
Returning : 6
Returning : 24
Returning : 120
Returning : 720
factorial(6) is Returned : 720
 
Enter a number:
7
Returned 1 .
Returning : 1
Returning : 2
Returning : 6
Returning : 24
Returning : 120
Returning : 720
Returning : 5040
factorial(7) is Returned : 5040
 
Enter a number:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值