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

in programming •  3 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

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  
  ·  3 years ago 

voted. here.

Thank you

hello, sir @justyy, today again I missed upvote from your trail. I'm an active delegator(66K SP) & voted you as witness. please, check the following post --

https://steemit.com/hive-129948/@rme/announcement-of-official-charity-account-of-amar-bangla-blog

  ·  3 years ago