How to resolve the algorithm Least common multiple step by step in the 8th programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Least common multiple step by step in the 8th 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 8th programming language
Source code in the 8th programming language
: gcd \ a b -- gcd
dup 0 n:= if drop ;; then
tuck \ b a b
n:mod \ b a-mod-b
recurse ;
: lcm \ m n
2dup \ m n m n
n:* \ m n m*n
n:abs \ m n abs(m*n)
-rot \ abs(m*n) m n
gcd \ abs(m*n) gcd(m.n)
n:/mod \ abs / gcd
nip \ abs div gcd
;
: demo \ n m --
2dup "LCM of " . . " and " . . " = " . lcm . ;
12 18 demo cr
-6 14 demo cr
35 0 demo cr
bye
You may also check:How to resolve the algorithm Zhang-Suen thinning algorithm step by step in the Racket programming language
You may also check:How to resolve the algorithm Klarner-Rado sequence step by step in the XPL0 programming language
You may also check:How to resolve the algorithm 9 billion names of God the integer step by step in the Python programming language
You may also check:How to resolve the algorithm Descending primes step by step in the Sidef programming language
You may also check:How to resolve the algorithm Guess the number/With feedback step by step in the C++ programming language