How to resolve the algorithm Least common multiple step by step in the OCaml programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Least common multiple step by step in the OCaml programming language
Table of Contents
Problem Statement
Compute the least common multiple (LCM) of two integers. Given m and n, the least common multiple is the smallest positive integer that has both m and n as factors.
The least common multiple of 12 and 18 is 36, because:
As a special case, if either m or n is zero, then the least common multiple is zero.
One way to calculate the least common multiple is to iterate all the multiples of m, until you find one that is also a multiple of n. If you already have gcd for greatest common divisor, then this formula calculates lcm.
One can also find lcm by merging the prime decompositions of both m and n.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Least common multiple step by step in the OCaml programming language
Source code in the ocaml programming language
let rec gcd u v =
if v <> 0 then (gcd v (u mod v))
else (abs u)
let lcm m n =
match m, n with
| 0, _ | _, 0 -> 0
| m, n -> abs (m * n) / (gcd m n)
let () =
Printf.printf "lcm(35, 21) = %d\n" (lcm 21 35)
You may also check:How to resolve the algorithm Rep-string step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm String concatenation step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Pythagorean triples step by step in the Perl programming language
You may also check:How to resolve the algorithm RIPEMD-160 step by step in the Racket programming language
You may also check:How to resolve the algorithm Harshad or Niven series step by step in the XPL0 programming language