a shot of dev knowledge

The smallest possible integer that can be divisible by any set of integers `n1, n2, n3, ...`

is the lcm of that set of numbers

Example: the LCM of 72 and 120 is 360.

In mathematics, the Least Common Multiple (LCM) of two integers is the smallest possible positive integer that is divisible by both integers.

In the code below, the integers are stored in `r1`

and `r2`

, respectively. The largest number in `r1`

and `r2`

is stored in `max`

, and the LCM of two numbers cannot be less than max.
The test expression of the `while loop`

is always true.

#include <stdio.h> int main() { int r1 = 14,r2 = 8, max; // maximum number between r1 and r2 is stored in min max = (r1 > r2) ? r1 : r2; while (1) { if (max % r1 == 0 && max % r2 == 0) { printf("The LCM of %d and %d is %d.", r1, r2, max); break; } ++max; } return 0; }

First, we assumed that the LCM is the first element of the array (set as result). Then, we passed the result and the second element to the `LCM()`

function. The result value has now been set as the return value and so, with the result and the third variable, we can call the `LCM()`

function once more.

#include <stdio.h> int LCM(int x,int y) { int n = 1; while(n%x || n%y) { n++; } return n; } void main() { int arr[] = {14, 8}; int val, s, j; s = sizeof(arr) / sizeof(int); val = arr[0]; for (j = 1; j < s; j++) { val = LCM(val, arr[j]); } printf("The LCM is %d.\n", val); }

RELATED COURSES

View all Courses

Related Courses

Related Courses

View all Courses

Keep Exploring

Related Courses