Python/maths/basic_maths.py

85 lines
1.6 KiB
Python
Raw Normal View History

"""Implementation of Basic Math in Python."""
2018-10-19 12:48:28 +00:00
import math
def prime_factors(n):
"""Find Prime Factors."""
2018-10-19 12:48:28 +00:00
pf = []
while n % 2 == 0:
pf.append(2)
n = int(n / 2)
for i in range(3, int(math.sqrt(n)) + 1, 2):
2018-10-19 12:48:28 +00:00
while n % i == 0:
pf.append(i)
n = int(n / i)
2018-10-19 12:48:28 +00:00
if n > 2:
pf.append(n)
2018-10-19 12:48:28 +00:00
return pf
def number_of_divisors(n):
"""Calculate Number of Divisors of an Integer."""
2018-10-19 12:48:28 +00:00
div = 1
2018-10-19 12:48:28 +00:00
temp = 1
while n % 2 == 0:
temp += 1
n = int(n / 2)
div = div * (temp)
for i in range(3, int(math.sqrt(n)) + 1, 2):
2018-10-19 12:48:28 +00:00
temp = 1
while n % i == 0:
temp += 1
n = int(n / i)
div = div * (temp)
2018-10-19 12:48:28 +00:00
return div
def sum_of_divisors(n):
"""Calculate Sum of Divisors."""
2018-10-19 12:48:28 +00:00
s = 1
2018-10-19 12:48:28 +00:00
temp = 1
while n % 2 == 0:
temp += 1
n = int(n / 2)
if temp > 1:
2019-10-05 05:14:13 +00:00
s *= (2 ** temp - 1) / (2 - 1)
for i in range(3, int(math.sqrt(n)) + 1, 2):
2018-10-19 12:48:28 +00:00
temp = 1
while n % i == 0:
temp += 1
n = int(n / i)
if temp > 1:
2019-10-05 05:14:13 +00:00
s *= (i ** temp - 1) / (i - 1)
2018-10-19 12:48:28 +00:00
return s
def euler_phi(n):
"""Calculte Euler's Phi Function."""
l = prime_factors(n)
2018-10-19 12:48:28 +00:00
l = set(l)
s = n
for x in l:
s *= (x - 1) / x
return s
2018-10-19 12:48:28 +00:00
def main():
"""Print the Results of Basic Math Operations."""
print(prime_factors(100))
print(number_of_divisors(100))
print(sum_of_divisors(100))
print(euler_phi(100))
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
2018-10-19 12:48:28 +00:00
main()