BASH Function to Compute the Greatest Common Divisor and Least Common Multiples


We can compute the Greatest Common Divisor (GCD) using Iterative Divide/Remainder Method. The following is the GCD implementation in BASH Programming:

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
 
function gcd() {
    local x=$1
    local y=$2
    while [ $y -gt 0 ]; do
        local t=$x
        x=$y
        y=$((t%y))
    done
    echo $x
}
#!/bin/bash

function gcd() {
    local x=$1
    local y=$2
    while [ $y -gt 0 ]; do
        local t=$x
        x=$y
        y=$((t%y))
    done
    echo $x
}

And the Least Common Multiples can be computed as the multipication of two integers divided by their GCD:

1
2
3
4
5
6
7
8
#!/bin/bash
 
function lcm() {
    local x=$1
    local y=$2
    local g=$(gcd $x $y)
    echo $((x*y/g))    
}
#!/bin/bash

function lcm() {
    local x=$1
    local y=$2
    local g=$(gcd $x $y)
    echo $((x*y/g))    
}

See also: Smallest Multiple Algorithm using Bruteforce or GCD/LCM

The GCD Program in BASH: BASH Function to Compute the Greatest Common Divisor and Least Common Multiples

BASH Programming/Shell

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
243 words
Last Post: Teaching Kids Programming: Number of Positions in Line of People
Next Post: Teaching Kids Programming - Count of Sublists with Same First and Last Values

The Permanent URL is: BASH Function to Compute the Greatest Common Divisor and Least Common Multiples

Leave a Reply