首页 > 其他 > 详细

计算阶乘

时间:2018-01-08 00:23:25      阅读:287      评论:0      收藏:0      [点我收藏+]
 1 package com.jdk7.chapter1;
 2 
 3 public class Factorial {
 4     /**
 5      * 计算n!的值,利用公式n×(n-1)×(n-2)×(n-3)×...×3×2×1
 6      * 注:当n大于17时n!会超出long的取值范围
 7      */
 8     public long getFactorial(int n){
 9         if(n<0 || n>17){
10             System.out.println("n的取值区间为[0,17]");
11             return -1;
12         }else if(n==0){
13             return 1;
14         }else{
15             long result = 1;
16             for(;n>0;n--){
17                 result *=n;
18             }
19             return result;
20         }
21         
22     }
23     
24     public static void main(String[] args) {
25         Factorial f = new Factorial();
26         System.out.println(f.getFactorial(4));
27         System.out.println(f.getFactorial(17));
28         System.out.println(f.getFactorial(18));
29         System.out.println(f.getFactorial(0));
30         System.out.println(f.getFactorial(-2));
31     }
32 
33 }
34 
35 执行结果:
36 24
37 355687428096000
38 n的取值区间为[0,17]
39 -1
40 1
41 n的取值区间为[0,17]
42 -1

 

计算阶乘

原文:https://www.cnblogs.com/celine/p/8232881.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!