- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathbasic_maths.py
122 lines (110 loc) · 3.04 KB
/
basic_maths.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"""Implementation of Basic Math in Python."""
importmath
defprime_factors(n: int) ->list:
"""Find Prime Factors.
>>> prime_factors(100)
[2, 2, 5, 5]
>>> prime_factors(0)
Traceback (most recent call last):
...
ValueError: Only positive integers have prime factors
>>> prime_factors(-10)
Traceback (most recent call last):
...
ValueError: Only positive integers have prime factors
"""
ifn<=0:
raiseValueError("Only positive integers have prime factors")
pf= []
whilen%2==0:
pf.append(2)
n=int(n/2)
foriinrange(3, int(math.sqrt(n)) +1, 2):
whilen%i==0:
pf.append(i)
n=int(n/i)
ifn>2:
pf.append(n)
returnpf
defnumber_of_divisors(n: int) ->int:
"""Calculate Number of Divisors of an Integer.
>>> number_of_divisors(100)
9
>>> number_of_divisors(0)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
>>> number_of_divisors(-10)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
"""
ifn<=0:
raiseValueError("Only positive numbers are accepted")
div=1
temp=1
whilen%2==0:
temp+=1
n=int(n/2)
div*=temp
foriinrange(3, int(math.sqrt(n)) +1, 2):
temp=1
whilen%i==0:
temp+=1
n=int(n/i)
div*=temp
ifn>1:
div*=2
returndiv
defsum_of_divisors(n: int) ->int:
"""Calculate Sum of Divisors.
>>> sum_of_divisors(100)
217
>>> sum_of_divisors(0)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
>>> sum_of_divisors(-10)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
"""
ifn<=0:
raiseValueError("Only positive numbers are accepted")
s=1
temp=1
whilen%2==0:
temp+=1
n=int(n/2)
iftemp>1:
s*= (2**temp-1) / (2-1)
foriinrange(3, int(math.sqrt(n)) +1, 2):
temp=1
whilen%i==0:
temp+=1
n=int(n/i)
iftemp>1:
s*= (i**temp-1) / (i-1)
returnint(s)
defeuler_phi(n: int) ->int:
"""Calculate Euler's Phi Function.
>>> euler_phi(100)
40
>>> euler_phi(0)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
>>> euler_phi(-10)
Traceback (most recent call last):
...
ValueError: Only positive numbers are accepted
"""
ifn<=0:
raiseValueError("Only positive numbers are accepted")
s=n
forxinset(prime_factors(n)):
s*= (x-1) /x
returnint(s)
if__name__=="__main__":
importdoctest
doctest.testmod()