Q:

How do you find the GCF in Python?

0

How do you find the GCF in Python

In this exercise, you will learn to find the greatest common divisor (G.C.D) or highest common factor (H.C.F) of numbers using different methods in Python.

Greatest common divisor (G.C.D) of two or more integers, which are not all zero, is the largest positive integer that divides each of the integers. For two integers a, b, the greatest common divisor of a and b is denoted gcd(a,b). These are different ways to find the GCD or HCF using Python.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

GCD in Python using math.gcd() Method

In Python, the math module contains various mathematical functions, which can be performed effortlessly utilizing the module. The math.gcd() method computes the greatest common divisor of two numbers.

Syntax 

math.gcd(x, y)

Here, x and y are non-negative integers for computing GCD. It returns a positive integer value representing the greatest common divisor (GCD) for two integers.

Example

import math

# Greatest common divisor of the two integers
print("GCD of (5, 2) = ",math.gcd(5, 2))
print("GCD of (4, 10) = ",math.gcd(4, 10))
print("GCD of (10, 0) = ",math.gcd(10, 0))
print("GCD of (-9, -16) = ",math.gcd(-9, -16))
print("GCD of (4, 14) = ",math.gcd(4, 14))
print("GCD of (6, 3) = ",math.gcd(6, 3))

Output of the above code -

GCD of (5, 2) =  1

GCD of (4, 10) =  2

GCD of (10, 0) =  10

GCD of (-9, -16) =  1

GCD of (4, 14) =  2

GCD of (6, 3) =  3

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Exercises, Practice Questions and Solutions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to multiply all elements in list Python?... >>
<< Write a python program to remove last element from...