forked from ghanteyyy/nppy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFactorial.py
62 lines (40 loc) · 1.49 KB
/
Factorial.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import math
class Factorial:
'''Factorial is the product of an integer and all the integers below. It is represented also by '!'
Example: Factorial of 5 or 5! = 5 * 4 * 3 * 2 * 1
= 120 '''
def __init__(self, number=5):
self.number = number
def method_one(self):
'''Using while loop'''
get_factorial = 1
nums = self.number
while nums != 1:
get_factorial *= nums
nums -= 1
return f'{self.number}! = {get_factorial}'
def method_two(self):
'''Using for loop'''
get_factorial = 1
for num in range(1, self.number + 1):
get_factorial *= num
return f'{self.number}! = {get_factorial}'
def method_three(self):
'''Using built-in <math> module'''
get_factorial = math.factorial(self.number)
return f'{self.number}! = {get_factorial}'
def method_four(self, number):
'''Using recursive method'''
if number == 1:
return number
return number * self.method_four(number - 1)
if __name__ == '__main__':
factorial = Factorial()
print('\nMethod One')
print(factorial.method_one())
print('\nMethod Two')
print(factorial.method_two())
print('\nMethod Three')
print(factorial.method_three())
print('\nMethod Four')
print(factorial.method_four(factorial.number))