Program for GCD of three numbers in python

Program for GCD of three numbers in Python

GCD of three numbers

GCD of three integers (where integers not equal to zero) is largest positive integer that divides each of the three integers. For example GCD of 12 , 16 , 22 is 2 where factors of 12==>1,2,3,4,6,12
factors of 16==>1,2,4,8,16
factors of 22==>1,2,11,22
common factors==>1,2
greatest common factor==>2

Working:

  • Step 1: Import math module
  • Step 2: Read the first number
  • Step 3: Read the second number
  • Step 4: Read the third number
  • Step 5: Print the gcd of three numbers by using in-built gcd function . find gcd of two numbers and then find the gcd of remaing number and gcd of two numbers which gives gcd of three numbers

Python code:

Solution 1:

import math
n1=int(input(“ENTER THE FIRST NUMBER “))
n2=int(input(“ENTER SECOND NUMBER “))
n3=int(input(“ENTER THIRD NUMBER “))
print(“THE GCD OF GIVEN NUMBERS:”,math.gcd(math.gcd(n1,n2),n3))
ENTER THE FIRST NUMBER 12
ENTER SECOND NUMBER 16
ENTER THIRD NUMBER 22
GCD of given two numbers is: 2

Working :

  • Step 1: Create a function gcd which calculates gcd of two numbers using euclidean algorithm
  • Step 2: Read the first number
  • Step 3: Read the second number
  • Step 4: Read the third number
  • Step 5: Call the function gcd to calculate gcd of last two numbers and again call the same function to calculate gcd of first number and gcd of last two numbers which gives gcd of three numbers.

Solution 2:

def gcd(n1,n2):
    if(n1==0):
        return n2
    else:
        return gcd(n2%n1,n1)
n1=int(input(“ENTER THE FIRST NUMBER “))
n2=int(input(“ENTER SECOND NUMBER “))
n3=int(input(“ENTER THIRD NUMBER “))
print(“GCD of given two numbers is:”,gcd(n1,gcd(n2,n3)))
ENTER THE FIRST NUMBER 12
ENTER SECOND NUMBER 16
ENTER THIRD NUMBER 22
GCD of given two numbers is: 2