| 1 | #!/bin/bash |
| 2 | # gcd.sh: greatest common divisor |
| 3 | # Uses Euclid's algorithm |
| 4 | |
| 5 | # The "greatest common divisor" (gcd) of two integers |
| 6 | #+ is the largest integer that will divide both, leaving no remainder. |
| 7 | |
| 8 | # Euclid's algorithm uses successive division. |
| 9 | # In each pass, |
| 10 | #+ dividend <--- divisor |
| 11 | #+ divisor <--- remainder |
| 12 | #+ until remainder = 0. |
| 13 | # The gcd = dividend, on the final pass. |
| 14 | # |
| 15 | # For an excellent discussion of Euclid's algorithm, see |
| 16 | #+ Jim Loy's site, http://www.jimloy.com/number/euclids.htm. |
| 17 | |
| 18 | |
| 19 | # ------------------------------------------------------ |
| 20 | # Argument check |
| 21 | ARGS=2 |
| 22 | E_BADARGS=85 |
| 23 | |
| 24 | if [ $# -ne "$ARGS" ] |
| 25 | then |
| 26 | echo "Usage: `basename $0` first-number second-number" |
| 27 | exit $E_BADARGS |
| 28 | fi |
| 29 | # ------------------------------------------------------ |
| 30 | |
| 31 | |
| 32 | gcd () |
| 33 | { |
| 34 | |
| 35 | dividend=$1 # Arbitrary assignment. |
| 36 | divisor=$2 #! It doesn't matter which of the two is larger. |
| 37 | # Why not? |
| 38 | |
| 39 | remainder=1 # If an uninitialized variable is used inside |
| 40 | #+ test brackets, an error message results. |
| 41 | |
| 42 | until [ "$remainder" -eq 0 ] |
| 43 | do # ^^^^^^^^^^ Must be previously initialized! |
| 44 | let "remainder = $dividend % $divisor" |
| 45 | dividend=$divisor # Now repeat with 2 smallest numbers. |
| 46 | divisor=$remainder |
| 47 | done # Euclid's algorithm |
| 48 | |
| 49 | } # Last $dividend is the gcd. |
| 50 | |
| 51 | |
| 52 | gcd $1 $2 |
| 53 | |
| 54 | echo; echo "GCD of $1 and $2 = $dividend"; echo |
| 55 | |
| 56 | |
| 57 | # Exercises : |
| 58 | # --------- |
| 59 | # 1) Check command-line arguments to make sure they are integers, |
| 60 | #+ and exit the script with an appropriate error message if not. |
| 61 | # 2) Rewrite the gcd () function to use local variables. |
| 62 | |
| 63 | exit 0 |