A Shell program To Find The GCD | Linux

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
filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


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


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.