63.8k views
3 votes
Write a Linux script that reads two integer numbers A and B then:

A) [5p] Computes their Greatest Common Divisor (GCD)
B) [5p] Computes their Lowest Common Multiple (LCM)

1 Answer

2 votes

Final answer:

To compute the GCD and LCM of two integers A and B in Linux, you can write a Bash script with functions for GCD and LCM. The script reads the input numbers, calculates the GCD using recursion, and then finds the LCM using the GCD.

Step-by-step explanation:

The script to compute the Greatest Common Divisor (GCD) and Lowest Common Multiple (LCM) of two integer numbers A and B in Linux is as follows:

#!/bin/bash

# Function to compute GCD
gcd() {
if [ $2 -eq 0 ]; then
echo $1
else
gcd $2 $(($1 % $2))
fi
}

# Function to compute LCM
lcm() {
echo $(( $1 * $2 / $(gcd $1 $2) ))
}

# Read two integer numbers
read -p "Enter the first number (A): " a
read -p "Enter the second number (B): " b

# Compute GCD
GCD_RESULT=$(gcd $a $b)
echo "The GCD of $a and $b is: $GCD_RESULT"

# Compute LCM
LCM_RESULT=$(lcm $a $b)
echo "The LCM of $a and $b is: $LCM_RESULT"

First, call the script GCD_LCM.sh. To execute the script, you might need to give it execution permissions with the command chmod +x GCD_LCM.sh and then run it using ./GCD_LCM.sh. The script defines two functions gcd() for computing the Greatest Common Divisor and lcm() for computing the Lowest Common Multiple. It then prompts the user to input two integer numbers A and B, computes the GCD by recursively calling the gcd() function, and calculates the LCM based on the GCD and the input numbers.

User Adam Obeng
by
8.2k points

Related questions