majianyu
4/29/2018 - 3:16 PM

## EX1.1.20

0的阶乘等于1

5! = 6!/6

4! = 5!/5

3! = 4!/4

2! = 3!/3

1! = 2!/2

0! = 1!/1 = 1

``````def factorial(n: int) -> int:
# 递归实现
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

def factorial_loop(n: int) -> int:
# 迭代实现
if n == 0 :
return 1;
else :
result = 1
for i in range(n,0,-1):
result *= i
return result

if __name__ == '__main__':
print(factorial(5))
print(factorial_loop(5))``````
``````package main

import "fmt"

func main() {
fmt.Println(factorial(5))
fmt.Println(factorialLoop(5))
}
func factorial(n int64) int64 {
// 递归实现
if n == 1 || n == 0 {
return 1
} else {
return n * factorial(n-1)
}
}
func factorialLoop(n int64) int64 {
// 迭代实现
if n == 0 {
return 1;
}
var result int64 = 1
for i := n; i > 0; i-- {
result *= i
}
return result
}
``````
``````package com.test;

public class Factorial {
public static void main(String[] args) {
System.out.println(factorial(5));
System.out.println(factorialLoop(5));
}

private static long factorial(int n) {
// 递归实现
if (n == 1 || n == 0) {
return 1;
} else{
return n * factorial(n - 1);
}
}

private static long factorialLoop(int n) {
// 迭代实现
if (n == 0) {
return 1;
}
long result = 1;
for (int i = n; i > 0; i--) {
result *= i;
}
return result;
}
}``````