GCD In Python

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 51:- GCD In Python

In Python, you can find the greatest common divisor (GCD) of two or more numbers using the math.gcd() function from the math 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 numbers a and b as input and uses the math.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.

6. Loops

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?