计算阶乘

本文介绍了一个简单的Java程序,用于计算阶乘。该程序定义了一个名为Factorial的类,其中包含一个getFactorial方法,用于计算从1到指定整数n的阶乘。文章通过示例演示了如何使用此方法,并指出了当输入值超过17时,结果将超出long类型的最大值。
 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值