赞
踩
求一个数的阶乘,比如给一个6,求6的阶乘,数学计算公式是6x5x4x3x2x1=120.今天用程序实现了下,分别是递归和循环的方式实现的,代码如下:
package suanfa; /** * 求N的阶乘 */ public class N { public static void main(String[] args) { int n = 6; //递归算法 int num = jiechen(n); System.out.println(num); //非递归 int jiechen2 = jiechen2(n); System.out.println(jiechen2); } /** * 计算i的阶乘,非递归算法. * @param num */ private static int jiechen2(int num) { int result = 1; int firstNum; int secondNum; for (int i =1;i<=num;) { firstNum = i; secondNum = i+1; if (firstNum <= num) { result *= firstNum; } if (secondNum <= num) { result *= secondNum; } i = i+2; } return result; } private static int jiechen(int i) { if (i == 0) { return 1; } return i * jiechen(i - 1); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。