Friday, August 14, 2009

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

4 comments:

  1. Thanks for sharing your scripts.
    It is easy for beginners.

    ReplyDelete
  2. Hello There,

    Jeez oh man,while I applaud for your writing , it’s just so damn straight to the point GCD of more than two numbers.
    Getting below exception while installing DreamHouse app from AppExchange

    Method does not exist or incorrect signature : void isRunningTest() from the type Test
    EinsteinVisionController: Method does not exist or incorrect signature: void isRunningTest() from the type Test

    Very useful article, if I run into challenges along the way, I will share them here.

    Thanks a heaps,
    Preethi.

    ReplyDelete
  3. Great post. I found your website perfect for my needs

    ReplyDelete