给定的问题在fico安置面试回合中提出。使用shell脚本查找两个给定数字的gcd
我们给了两个数字A和B,现在的任务是使用Shell脚本找到两个给定数字的最大公约数(gcd)。
采访中询问:FICO
例子:
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
上面代码的shell脚本是:
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