Here I will be able to show you four other ways to seek out GCD in Python victimization program examples.
GCD is also called HCF (Highest Common Factor). therefore let’s see however we’ll bonk.
Method 1: Using Loop
n1 = 48
n2 = 36
#find smaller
if(n1>n2):
smaller = n2
else:
smaller = n1
#getting hcf
i = 1
while(i<=smaller):
if(n1%i==0 and n2%i ==0):
hcf = i
i = i+1
print("hcf = ", hcf)
Output
hcf = 12
So during this program, initial we have a tendency to assign values to n1 and n2, then we’ll notice smaller variety from each of the numbers. afterward we’ll begin loop from one to smaller number to seek out variety which may be absolutely partible with each of the numbers n1 and n2 and store into a brand new variable named as hcf. At the top of the loop, we’ll get the best variety to keep in hcf variable which may absolutely divide each of the numbers n1 and n2. That highest variety is our hcf.
Method 2: Using Recursion
def find_hcf(n1,n2):
if(n2==0):
return n1
else:
return find_hcf(n2,n1%n2)
n1 = 48
n2 = 36
hcf = find_hcf(n1,n2)
print ("highest common factor = ", hcf)
Output
highest common factor = 12
So here we’ve a algorithmic perform that receive 2 arguments and come to the best common divisor between them.
Method 3: Using math.gcd()
import math
n1 = 48
n2 = 36
hcf = math.gcd(n1,n2)
print("Highest Common Factor = ", hcf)
Output
Highest Common Factor = 12
Python has an associate intrinsical methodology to seek out out the GCD. we have a tendency to even doesn’t got to suppose a way to code to seek out GCD. All we’ve to try to do is simply use science.gcd() methodology and it’ll come to the GCD.
Method 4: Using the Euclidean Algorithm
Pseudocode:
function gcd(a, b)
while b ≠ 0
t := b;
b := a mod b;
a := t;
return a;
Program:
#implementing Euclidean algo
def get_gcd (x, y):
while(y):
x, y = y, x % y
return x
n1 = 48
n2 = 36
hcf = get_gcd(n1,n2)
print("Highest Common Factor = ", hcf)
Output:
Highest Common Factor = 12
Euclid’s algorithmic rule is an associate economical methodology for computing the best common measure (GCD) of 2 numbers.
Here is that the pseudocode to indicate how we will notice GCD victimization geometer algorithmic rule.
In this program, get_gcd(int, int) perform is employed to implement the geometer algorithmic rule
If you’ve any downside or suggestion associated with python gcd programs then comment down below.