Skip to content
Related Articles

Related Articles

Improve Article

A Shell program To Find The GCD | Linux

  • Difficulty Level : Hard
  • Last Updated : 18 Jan, 2021

The given problem asked in fico placement interview round. Find the gcd of two given numbers using shell scripting 
We are given two numbers A and B and now task is to find the Greatest Common divisor (gcd) of two given number using shell scripting .
Asked in interview : FICO
Example: 
 

Input
 25 15
Output
 5

 

CPP




// Script for finding gcd of two number
// echo is for printing the message 
echo Enter two numbers with space in between
 
// read for scanning
read a b
 
// Assigning the value of a to m
m = $a
 
// Condition checking if b greater than m
// If yes the replace the value of m assign a new value
if [ $b -lt $m ]
then
m = $b
fi
 
// In do while  loop we are checking the gcd
while [ $m -ne 0 ]
do
x = `expr $a % $m`
y = `expr $b % $m`
 
// If x and y both are 0 then we complete over
// process and we print  the gcd
if [ $x -eq 0 -a $y -eq 0 ]
then
 
// Printing the greatest gcd of two given number
echo gcd of $a and $b is $m
break
fi
m = `expr $m - 1`
 
done

The shell script for the above code is :

echo Enter two numbers with space in between
read a b
//reads numbers
m=$a
if [ $b -lt $m ]
then
m=$b
fi
while [ $m -ne 0 ]
do
x=`expr $a % $m`
y=`expr $b % $m`
if [ $x -eq 0 -a $y -eq 0 ]
then
echo gcd of $a and $b is $m
break
fi
m=`expr $m - 1`
done

This article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

My Personal Notes arrow_drop_up
Recommended Articles
Page :