Write a Python program that calculates the greatest common divisor of two numbers and…
- User
Write a Python program that calculates the greatest common divisor of two numbers and displays the result. 10 and 20
Assistant
Write a Python program that calculates the greatest common divisor of two numbers and displays the result. 10 and 20
Problem: Write a Python program that calculates the greatest common divisor of two numbers and displays the result. 10 and 20
Approach: Selection: Euclidean Algorithm
Key considerations:
Complexity: - Alternative considered: Brute force (O(n)) was rejected due to inefficiency with large numbers
Let me implement this solution.
"""
Greatest Common Divisor (GCD) Calculator
Uses the Euclidean Algorithm for efficient computation.
"""
def calculate_gcd(a: int, b: int) -> int:
"""
Calculate the Greatest Common Divisor of two integers.
Uses the Euclidean algorithm: GCD(a, b) = GCD(b, a mod b)
Args:
a: First integer
b: Second integer
Returns:
The GCD of a and b (always positive)
Examples:
>>> calculate_gcd(10, 20)
10
>>> calculate_gcd(48, 18)
6
"""
# Work with absolute values (GCD is always positive)
a, b = abs(a), abs(b)
# Euclidean algorithm
while b != 0:
a, b = b, a % b
return a
def display_gcd(num1: int, num2: int) -> None:
"""
Calculate and display the GCD of two numbers in a user-friendly format.
Args:
num1: First number
num2: Second number
"""
result = calculate_gcd(num1, num2)
print(f"{'='*40}")
print(f" GCD Calculator")
print(f"{'='*40}")
print(f" Number 1: {num1}")
print(f" Number 2: {num2}")
print(f"{'─'*40}")
print(f" Greatest Common Divisor: {result}")
print(f"{'='*40}")
# Main execution
if __name__ == "__main__":
# Calculate GCD for 10 and 20
number1 = 10
number2 = 20
display_gcd(number1, number2)
========================================
GCD Calculator
========================================
Number 1: 10
Number 2: 20
----------------------------------------
Greatest Common Divisor: 10
========================================
| Step | a | b | a % b |
|---|---|---|---|
| 1 | 10 | 20 | 10 |
| 2 | 20 | 10 | 0 |
| 3 | 10 | 0 | - |
Result: GCD(10, 20) = 10 ✓
The factors of 10 are {1, 2, 5, 10} and the factors of 20 are {1, 2, 4, 5, 10, 20}. The greatest common factor is 10.