How to resolve the algorithm Greatest common divisor step by step in the UNIX Shell programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Greatest common divisor step by step in the UNIX Shell programming language

Table of Contents

Problem Statement

Find the greatest common divisor   (GCD)   of two integers.

Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Greatest common divisor step by step in the UNIX Shell programming language

Source code in the unix programming language

gcd() {
	# Calculate $1 % $2 until $2 becomes zero.
	until test 0 -eq "$2"; do
		# Parallel assignment: set -- 1 2
		set -- "$2" "`expr "$1" % "$2"`"
	done

	# Echo absolute value of $1.
	test 0 -gt "$1" && set -- "`expr 0 - "$1"`"
	echo "$1"
}

gcd -47376 87843
# => 987

gcd() { until test 0 -eq "$2";do set -- "$2" "$(($1 % $2))";done;if [ 0 -gt "$1" ];then echo "$((- $1))";else  echo "$1"; fi }

gcd -47376 87843
# => 987

gcd () { if [ "$2" -ne 0 ];then gcd "$2" "$(($1 % $2))";else echo "$1";fi }

gcd 100 75
# => 25

alias gcd eval \''set gcd_args=( \!*:q )	\\
	@ gcd_u=$gcd_args[2]			\\
	@ gcd_v=$gcd_args[3]			\\
	while ( $gcd_v != 0 )			\\
		@ gcd_t = $gcd_u % $gcd_v	\\
		@ gcd_u = $gcd_v		\\
		@ gcd_v = $gcd_t		\\
	end					\\
	if ( $gcd_u < 0 ) @ gcd_u = - $gcd_u	\\
	@ $gcd_args[1]=$gcd_u			\\
'\'

gcd result -47376 87843
echo $result
# => 987

  

You may also check:How to resolve the algorithm Polynomial long division step by step in the Go programming language
You may also check:How to resolve the algorithm Stack step by step in the jq programming language
You may also check:How to resolve the algorithm Integer comparison step by step in the PL/I programming language
You may also check:How to resolve the algorithm Digital root step by step in the VBA programming language
You may also check:How to resolve the algorithm Integer sequence step by step in the PowerShell programming language