求阶乘

190次阅读  |  发布于3年以前

题目:整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积

,0的阶乘为1。即:n!=1×2×3×...×n。

python3实现


#!/usr/bin/python3
#整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,0的阶乘为1。即:n!=1×2×3×...×n。

num = int(input("请输入数字:"))
fatorial = 1
if(num < 0):
    raise Exception("负数没有阶乘")
elif(num == 0):
    print("0的阶乘是1")
else:
    for i  in range(1,num+1):
        fatorial = fatorial*i
    print("%d的阶乘是%d"%(num,fatorial))




Java实现


package org.java.base.algorithm;

import java.util.Scanner;

/**
 * @ClassName Factorial
 * @Description TODO
 * @Author liuhaihua
 * @Date 2021/7/8 14:41
 * @Version 1.0
 */
public class Factorial {

  public  static   void main(String[] xargs)  throws Exception{
    Scanner  sc =  new Scanner(System.in);
    System.out.println("请输入数字:");
    int num =Integer.valueOf(sc.nextInt());
    int factorial =1;
    if(num<0){
      throw new Exception("负数没有阶乘");
    }
    if(num==0){
      factorial =1;
    }
    if(num>0) {
      for (int i = 1; i <= num; i++) {
        factorial = factorial*i;
      }
    }
    System.out.printf("%d的阶乘是%d",num,factorial);

  }
}

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8