Showing posts with label numbers. Show all posts
Showing posts with label numbers. Show all posts
Tuesday, February 7, 2017
GCD of more than two numbers
GCD of more than two numbers
#!/bin/bash
#**********************************************************************************************
# gcd.sh: greatest common divisor uses Eclidean algorithm
# Usage : gcd.sh num1 num2 num3 .... (any number of arguments)
# The algorithm used to calculate the GCD two integers is known as the Euclidean algorithm.
# Based on Euclidean algorithm this script is written(Recursive method).
# For checking supplied arguments are integers or not check GCD of two numbers code
#***********************************************************************************************
# Argument check
# Minimum 2 arguments you should to supply
ARGS=2
BADARGS=65
if [ $# -lt "$ARGS" ]
then
echo
echo "Invalid Arguments"
echo "Usage: $0 first-number second-number"
echo
exit $BADARGS
fi
# Preserve command line argument for future use
cmdargs=$*
function Euclidean()
{
if [ $2 -eq 0 ]
then
return $1
else
Euclidean $2 $(($1%$2)) # calling function recursively
fi
}
Euclidean $1 $2
return=$?
# $? returns the exit status of script. This is one method to capture return value of a function
shift
# Shifts command line arguments one step.Now $1 holds second argument
while true
do
shift
# shift is used to pick up next command line argument to continue iteration
# $# holds total number of arguments.At every shift operation its value decreases one
if [ $# -eq 0 ]
then
break 2
fi
Euclidean $return $1
return=$?
done
echo "GCD of $cmdargs is $return"
exit 0
Available link for download
Subscribe to:
Posts (Atom)