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

in #programming4 years ago

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

#!/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:

#!/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

--EOF (The Ultimate Computing & Technology Blog) --

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Coin Marketplace

STEEM 0.17
TRX 0.24
JST 0.034
BTC 96442.29
ETH 2762.51
SBD 0.65