Bash Script to Find LCM of Two Numbers
lcm = (a * b) / gcd. For example: gcd() { while [ $b -ne 0 ]; do t=$b; b=$((a % b)); a=$t; done; echo $a; }; lcm=$(( (num1 * num2) / $(gcd) )).Examples
How to Think About It
LCM = (number1 * number2) / GCD. This works because the product of two numbers equals the product of their GCD and LCM.Algorithm
Code
#!/bin/bash read -p "Enter two numbers: " a b function gcd() { local x=$1 local y=$2 while [ $y -ne 0 ]; do local temp=$y y=$(( x % y )) x=$temp done echo $x } g=$(gcd $a $b) lcm=$(( (a * b) / g )) echo "LCM of $a and $b is $lcm"
Dry Run
Let's trace the input 6 and 8 through the code
Input numbers
a=6, b=8
Calculate GCD
x=6, y=8; y != 0, temp=8; y=6%8=6; x=8 x=8, y=6; y != 0, temp=6; y=8%6=2; x=6 x=6, y=2; y != 0, temp=2; y=6%2=0; x=2 GCD=2
Calculate LCM
LCM = (6 * 8) / 2 = 48 / 2 = 24
| Iteration | x | y | temp | y after modulo |
|---|---|---|---|---|
| 1 | 6 | 8 | 8 | 6 |
| 2 | 8 | 6 | 6 | 2 |
| 3 | 6 | 2 | 2 | 0 |
Why This Works
Step 1: Why find GCD first?
The GCD helps us find the LCM because the product of two numbers equals the product of their GCD and LCM.
Step 2: How Euclidean algorithm works
It repeatedly replaces the larger number by the remainder of dividing the larger by the smaller until the remainder is zero, leaving the GCD.
Step 3: Calculating LCM
Divide the product of the two numbers by their GCD to get the LCM.
Alternative Approaches
#!/bin/bash read -p "Enter two numbers: " a b max=$(( a > b ? a : b )) while true; do if (( max % a == 0 && max % b == 0 )); then echo "LCM of $a and $b is $max" break fi ((max++)) done
#!/bin/bash read -p "Enter two numbers: " a b gcd=$(echo "define gcd(a,b){if(b==0)return a; return gcd(b,a%b);} gcd($a,$b)" | bc) lcm=$(( (a * b) / gcd )) echo "LCM of $a and $b is $lcm"
Complexity: O(log(min(a,b))) time, O(1) space
Time Complexity
The Euclidean algorithm for GCD runs in O(log(min(a,b))) time, which dominates the calculation. The LCM calculation is a simple arithmetic operation.
Space Complexity
The script uses a fixed number of variables and no extra data structures, so space complexity is O(1).
Which Approach is Fastest?
Using the Euclidean algorithm for GCD and then calculating LCM is faster than looping through multiples, especially for large numbers.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Euclidean GCD + formula | O(log(min(a,b))) | O(1) | Efficient for all input sizes |
| Loop checking multiples | O(n) worst case | O(1) | Simple but slow for large numbers |
| Using bc calculator | Depends on bc implementation | O(1) | When bc is available and for complex math |