If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, you can find the greatest common divisor (GCD) of two or more numbers using the
math.gcd()
function from themath
module. The GCD is the largest positive integer that divides both numbers without leaving a remainder.Here's an example of how to find the GCD of two numbers:
pythonCopy code
import math def find_gcd(a, b): return math.gcd(a, b) # Example usage: num1 = 24 num2 = 36 gcd_result = find_gcd(num1, num2) print(f"The GCD of {num1} and {num2} is: {gcd_result}")
Output:
csharpCopy code
The GCD of 24 and 36 is: 12
In this example, the
find_gcd()
function takes two numbersa
andb
as input and uses themath.gcd()
function to calculate their GCD. The function returns the GCD as the result.To find the GCD of more than two numbers, you can simply call the
math.gcd()
function multiple times, passing the result of the previous GCD calculation and the next number as arguments.pythonCopy code
import math def find_gcd(*args): result = args[0] for num in args[1:]: result = math.gcd(result, num) return result # Example usage: num1 = 24 num2 = 36 num3 = 48 gcd_result = find_gcd(num1, num2, num3) print(f"The GCD of {num1}, {num2}, and {num3} is: {gcd_result}")
Output:
csharpCopy code
The GCD of 24, 36, and 48 is: 12
In this example, the
find_gcd()
function uses variable-length arguments (*args
) to accept any number of input arguments. It then iterates through each argument, calculating the GCD one by one and updating the result. The final result is the GCD of all the input numbers.
Comments: 0