LDP/LDP/guide/docbook/abs-guide/gcd.sh

64 lines
1.7 KiB
Bash
Raw Normal View History

2002-04-01 16:05:47 +00:00
#!/bin/bash
# gcd.sh: greatest common divisor
# Uses Euclid's algorithm
# The "greatest common divisor" (gcd) of two integers
#+ is the largest integer that will divide both, leaving no remainder.
# Euclid's algorithm uses successive division.
2008-11-23 22:43:47 +00:00
# In each pass,
#+ dividend <--- divisor
#+ divisor <--- remainder
#+ until remainder = 0.
# The gcd = dividend, on the final pass.
2002-04-01 16:05:47 +00:00
#
# For an excellent discussion of Euclid's algorithm, see
2006-05-19 16:11:49 +00:00
#+ Jim Loy's site, http://www.jimloy.com/number/euclids.htm.
2002-04-01 16:05:47 +00:00
# ------------------------------------------------------
# Argument check
ARGS=2
2008-11-23 22:43:47 +00:00
E_BADARGS=85
2002-04-01 16:05:47 +00:00
if [ $# -ne "$ARGS" ]
then
echo "Usage: `basename $0` first-number second-number"
exit $E_BADARGS
fi
# ------------------------------------------------------
gcd ()
{
2006-12-20 21:11:55 +00:00
dividend=$1 # Arbitrary assignment.
divisor=$2 #! It doesn't matter which of the two is larger.
# Why not?
2002-04-01 16:05:47 +00:00
2008-11-23 22:43:47 +00:00
remainder=1 # If an uninitialized variable is used inside
#+ test brackets, an error message results.
2002-04-01 16:05:47 +00:00
until [ "$remainder" -eq 0 ]
2008-11-23 22:43:47 +00:00
do # ^^^^^^^^^^ Must be previously initialized!
2002-04-01 16:05:47 +00:00
let "remainder = $dividend % $divisor"
2006-12-20 21:11:55 +00:00
dividend=$divisor # Now repeat with 2 smallest numbers.
2002-04-01 16:05:47 +00:00
divisor=$remainder
2006-12-20 21:11:55 +00:00
done # Euclid's algorithm
2002-04-01 16:05:47 +00:00
2006-12-20 21:11:55 +00:00
} # Last $dividend is the gcd.
2002-04-01 16:05:47 +00:00
gcd $1 $2
echo; echo "GCD of $1 and $2 = $dividend"; echo
2008-11-23 22:43:47 +00:00
# Exercises :
# ---------
# 1) Check command-line arguments to make sure they are integers,
#+ and exit the script with an appropriate error message if not.
# 2) Rewrite the gcd () function to use local variables.
2002-04-01 16:05:47 +00:00
exit 0