Question: #!/bin/bash # gcd.sh: greatest common divisor # Uses Euclid's algorithm # The greatest common divisor (gcd) of two integers #+ is the largest integer that

 #!/bin/bash # gcd.sh: greatest common divisor # Uses Euclid's algorithm #
#!/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.
# In each pass,
#+ dividend
#+ divisor
#+ until remainder = 0.
# The gcd = dividend, on the final pass.
#
# For an excellent discussion of Euclid's algorithm, see
#+ Jim Loy's site, http://www.jimloy.comumber/euclids.htm.
# ------------------------------------------------------
# Argument check
ARGS=2
E_BADARGS=85
if [ $# -ne "$ARGS" ]
then
echo "Usage: `basename $0` first-number second-number"
exit $E_BADARGS
fi
# ------------------------------------------------------
gcd ()
{
dividend=$1 # Arbitrary assignment.
divisor=$2 #! It doesn't matter which of the two is larger.
# Why not?
remainder=1 # If an uninitialized variable is used inside
#+ test brackets, an error message results.
until [ "$remainder" -eq 0 ]
do # ^^^^^^^^^^ Must be previously initialized!
let "remainder = $dividend % $divisor"
dividend=$divisor # Now repeat with 2 smallest numbers.
divisor=$remainder
done # Euclid's algorithm
} # Last $dividend is the gcd.
gcd $1 $2
echo; echo "GCD of $1 and $2 = $dividend"; echo
# 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.
exit 0
2) Use this script as a prototype for a writing a script to determine if a year is a leap year. A year is a leap year if the year is evenly divisible by 4 unless it is evenly divisible by 100 in which case it is not a leap year unless it is evenly divisible by 400 in which case it is a leap year

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!