Skip to content

Commit

Permalink
Add Euler's Totient Function and Visualization
Browse files Browse the repository at this point in the history
  • Loading branch information
Kritika75 authored Dec 24, 2024
1 parent df40677 commit 871e969
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 0 deletions.
70 changes: 70 additions & 0 deletions pysnippets/Mathematics/Euler Function/euler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import matplotlib.pyplot as plt
from math import gcd

def euler_totient_function(n):
"""
Calculate Euler's Totient Function φ(n), which is the count of integers
from 1 to n that are coprime with n.
Parameters:
n (int): Input number
Returns:
tuple: (Value of φ(n), List of coprime numbers)
"""
if n <= 0:
raise ValueError("Input must be a positive integer.")

original_n = n # Save the original value of n for coprime calculation
result = n
coprimes = []

# Check divisors up to √n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1

if n > 1:
result -= result // n

# Find coprimes using the original n
for i in range(1, original_n + 1):
if gcd(i, original_n) == 1:
coprimes.append(i)

return result, coprimes

def visualize_coprimes(n, coprimes):
"""
Visualize coprime numbers up to n using a bar chart.
Parameters:
n (int): Input number
coprimes (list): List of coprime numbers
"""
all_numbers = list(range(1, n + 1))
coprime_flags = [1 if num in coprimes else 0 for num in all_numbers]

plt.figure(figsize=(10, 6))
plt.bar(all_numbers, coprime_flags, color='skyblue', edgecolor='black', label='Coprime')
plt.title(f"Coprime Numbers Up to {n}", fontsize=16)
plt.xlabel("Numbers", fontsize=14)
plt.ylabel("Coprime (1 = Yes, 0 = No)", fontsize=14)
plt.xticks(range(1, n + 1, max(1, n // 10)))
plt.yticks([0, 1], labels=["Not Coprime", "Coprime"])
plt.grid(axis='y', linestyle='--', alpha=0.6)
plt.legend()
plt.show()

# Example usage
if __name__ == "__main__":
num = int(input("Enter a positive integer: "))
result, coprimes = euler_totient_function(num)
print(f"φ({num}) = {result}")
print(f"Coprime numbers up to {num}: {coprimes}")

visualize_coprimes(num, coprimes)
35 changes: 35 additions & 0 deletions pysnippets/Mathematics/Euler Function/test_euler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import unittest
from euler import euler_totient_function, visualize_coprimes

class TestEulerFunction(unittest.TestCase):

def test_phi_value(self):
# Test the Euler's Totient function value
self.assertEqual(euler_totient_function(1)[0], 1)
self.assertEqual(euler_totient_function(6)[0], 2)
self.assertEqual(euler_totient_function(9)[0], 6)
self.assertEqual(euler_totient_function(10)[0], 4)

def test_coprimes_list(self):
# Test the list of coprimes
self.assertEqual(euler_totient_function(9)[1], [1, 2, 4, 5, 7, 8])
self.assertEqual(euler_totient_function(10)[1], [1, 3, 7, 9])
self.assertEqual(euler_totient_function(6)[1], [1, 5])
self.assertEqual(euler_totient_function(1)[1], [1])

def test_invalid_input(self):
# Test invalid input
with self.assertRaises(ValueError):
euler_totient_function(0)
with self.assertRaises(ValueError):
euler_totient_function(-5)

def test_visualize_coprimes(self):
# Test the visualize_coprimes function
try:
visualize_coprimes(10, [1, 3, 7, 9])
except Exception as e:
self.fail(f"visualize_coprimes raised an exception: {e}")

if __name__ == "__main__":
unittest.main()

0 comments on commit 871e969

Please sign in to comment.