Friday, February 10, 2017

GCD of two nubers

GCD of two nubers


I written three different methods to calculate GCD of two numbers

Method 1:


#!/bin/bash
#*******************************************************************************************
# gcd.sh: greatest common divisor uses Eclidean algorithm
# Usage : gcd.sh number1 number2
# The algorithm used to calculate the GCD between two integers is known as the Euclidean
# algorithm(Recursive method).
#*******************************************************************************************

#----------------------------------------------------------------------
# Argument check
ARGS=2
BADARGS=65

if [ $# -ne "$ARGS" ]
then
echo ; echo "Invalid Arguments"
echo "Usage: $0 first-number second-number" ; echo
exit $BADARGS
fi

# Check supplied arguments are integers are not

isnumber()
{
if [ $1 -eq $1 2> /dev/null ]
then
:
# : is a null command.This is the shell equivalent of a "NOP"(do nothing)
else
echo -e " You supplied one bad argument "$1" is not a number"
echo -e "Usage: $0 first-number second-number "
exit $BADARGS
fi
}
isnumber $1
isnumber $2

# ---------------------------------------------------------------------

function Euclidean()
{
if [ $2 -eq 0 ]
then

return $1

else

Euclidean $2 $(($1%$2))
# calling function recursively
fi
}

Euclidean $1 $2

echo "gcd of $1 and $2 is $?"

# $? returns the exit status of script. This is one method to capture return value of a function

exit 0

Method 2:


#!/bin/bash
# gcd2.sh
# Usage: gcd2.sh number1 number2
# For argument check see method 1

gcd ()
{
dividend=$1
divisor=$2
# Arbitrary assignment.
#! It doesnt matter which of the two is larger.

remainder=1

# If uninitialized variable used in loop,it results in an error message
# on the first pass through loop.

if [ $divisor -eq 0 ]
then
echo "GCD of $dividend and $divisor = $dividend"
exit 0
fi

until [ "$remainder" -eq 0 ]
do
let "remainder = $dividend % $divisor"

# Now repeat with 2 smallest numbers

dividend=$divisor .
divisor=$remainder
done
}
# Last $dividend is the gcd.

gcd $1 $2

echo; echo "GCD of $1 and $2 = $dividend"; echo
exit 0

Method 3:


#!/bin/bash
# gcd3.sh
# Usage: gcd3.sh
# This script doesnt use command line arguments.You should to enter two numbers when asking

echo enter two numbers
read n1 n2
remainder=1
# Preserve numbers for future use
t1=$n1
t2=$n2
if [ $n2 -eq 0 ]
then
echo "GCD of $n1 and $n2 = $n1"
exit 0
fi
while [ $remainder -ne 0 ]
do
remainder=`expr $n1 % $n2`
# or use
#remainder=$((n1%n2))
n1=$n2
n2=$remainder
done
echo "GCD of $t1 , $t2 is $n1"

Available link for download