Print the LCM
In this final step, you will run the LCM program and verify its output for different input combinations. We'll test the program with various integer pairs to demonstrate the LCM calculation.
Compile the program (if not already compiled):
cd ~/project
gcc lcm.c -o lcm
Run the program with different input combinations:
./lcm << EOF
12
18
EOF
Example output for 12 and 18:
Enter two positive integers:
First number: 12
Second number: 18
The Least Common Multiple of 12 and 18 is: 36
Let's try another example:
./lcm << EOF
15
25
EOF
Example output for 15 and 25:
Enter two positive integers:
First number: 15
Second number: 25
The Least Common Multiple of 15 and 25 is: 75
Key points to understand:
- The LCM is the smallest positive integer that is divisible by both input numbers
- For 12 and 18, the LCM is 36
- For 15 and 25, the LCM is 75
- The program uses the formula LCM(a,b) = (a*b)/GCD(a,b)
To make the program more robust, you can add input validation:
nano lcm.c
Update the main()
function to include input validation:
int main() {
int a, b, lcm;
printf("Enter two positive integers:\n");
printf("First number: ");
scanf("%d", &a);
printf("Second number: ");
scanf("%d", &b);
// Input validation
if (a <= 0 || b <= 0) {
printf("Error: Please enter positive integers only.\n");
return 1;
}
lcm = calculateLCM(a, b);
printf("The Least Common Multiple of %d and %d is: %d\n", a, b, lcm);
return 0;
}
Recompile and test the updated program:
gcc lcm.c -o lcm
./lcm