Least common multiple: Difference between revisions
→{{header|Standard ML}}: add another SML version
m (→{{header|J}}) |
(→{{header|Standard ML}}: add another SML version) |
||
(12 intermediate revisions by 9 users not shown) | |||
Line 40:
=={{header|11l}}==
<
L b != 0
(a, b) = (b, a % b)
Line 48:
R m I/ gcd(m, n) * n
print(lcm(12, 18))</
{{out}}
Line 59:
For maximum compatibility, this program uses only the basic instruction set (S/360)
with 2 ASSIST macros (XDECO,XPRNT).
<
USING LCM,R15 use calling register
L R6,A a
Line 88:
XDEC DS CL12 temp for edit
YREGS
END LCM</
{{out}}
<pre>
Line 95:
=={{header|8th}}==
<
: gcd \ a b -- gcd
dup 0 n:= if drop ;; then
Line 120:
bye</
{{out}}
<pre>LCM of 18 and 12 = 36
Line 128:
=={{header|Action!}}==
<
CARD tmp,c
Line 159:
Test(1,56)
Test(12,0)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Least_common_multiple.png Screenshot from Atari 8-bit computer]
Line 172:
=={{header|Ada}}==
lcm_test.adb:
<
procedure Lcm_Test is
Line 199:
Put_Line ("LCM of -6, 14 is" & Integer'Image (Lcm (-6, 14)));
Put_Line ("LCM of 35, 0 is" & Integer'Image (Lcm (35, 0)));
end Lcm_Test;</
Output:
Line 207:
=={{header|ALGOL 68}}==
<
BEGIN
PROC gcd = (INT m, n) INT :
Line 223:
"and their greatest common divisor is", gcd(m,n)))
END
</syntaxhighlight>
{{out}}
<pre>
Line 233:
=={{header|ALGOL W}}==
<
integer procedure gcd ( integer value a, b ) ;
if b = 0 then a else gcd( b, a rem abs(b) );
Line 241:
write( lcm( 15, 20 ) );
end.</
=={{header|APL}}==
APL provides this function.
<
36</
If for any reason we wanted to reimplement it, we could do so in terms of the greatest common divisor by transcribing the formula set out in the task specification into APL notation:
<
12 LCM 18
36</
=={{header|AppleScript}}==
<
-- lcm :: Integral a => a -> a -> a
Line 300:
result's |λ|(abs(x), abs(y))
end gcd</
{{Out}}
<syntaxhighlight lang="applescript">36</syntaxhighlight>
=={{header|Arendelle}}==
Line 318:
=={{header|Arturo}}==
<
x * y / gcd @[x y]
]
print lcm 12 18</
{{out}}
Line 330:
=={{header|Assembly}}==
==={{header|x86 Assembly}}===
<
; lcm.asm: calculates the least common multiple
; of two positive integers
Line 422:
ret
</syntaxhighlight>
=={{header|ATS}}==
Line 428:
Compile with ‘patscc -o lcm lcm.dats’
<
#include "share/atspre_define.hats"
Line 529:
assertloc (lcm (12, 22) = 132ULL);
assertloc (lcm (7ULL, 31ULL) = 217ULL)
end</
=={{header|AutoHotkey}}==
<
{
If (Number1 = 0 || Number2 = 0)
Line 544:
Num1 = 12
Num2 = 18
MsgBox % LCM(Num1,Num2)</
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
Func _LCM($a, $b)
Local $c, $f, $m = $a, $n = $b
Line 561:
Return $m * $n / $b
EndFunc ;==>_LCM
</syntaxhighlight>
Example
<syntaxhighlight lang="autoit">
ConsoleWrite(_LCM(12,18) & @LF)
ConsoleWrite(_LCM(-5,12) & @LF)
ConsoleWrite(_LCM(13,0) & @LF)
</syntaxhighlight>
<pre>
36
Line 576:
=={{header|AWK}}==
<
function gcd(m, n, t) {
# Euclid's method
Line 597:
# Read two integers from each line of input.
# Print their least common multiple.
{ print lcm($1, $2) }</
Example input and output: <pre>$ awk -f lcd.awk
Line 612:
==={{header|Applesoft BASIC}}===
ported from BBC BASIC
<
20 INPUT"M=";M%
30 INPUT"N=";N%
Line 633:
250 NEXT B
260 R = ABS(A%)
270 RETURN</
==={{header|BBC BASIC}}===
{{Works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbc basic">
DEF FN_LCM(M%,N%)
IF M%=0 OR N%=0 THEN =0 ELSE =ABS(M%*N%)/FN_GCD_Iterative_Euclid(M%, N%)
Line 649:
ENDWHILE
= ABS(A%)
</syntaxhighlight>
==={{header|IS-BASIC}}===
<
110 DEF GCD(A,B)
120 DO WHILE B>0
Line 659:
150 LET GCD=A
160 END DEF
170 PRINT LCM(12,18)</
==={{header|Tiny BASIC}}===
{{works with|TinyBasic}}
<syntaxhighlight lang="basic">10 PRINT "First number"
20 INPUT A
30 PRINT "Second number"
Line 681 ⟶ 682:
140 LET Q=R
150 LET R=C
160 GOTO 70</
=={{header|BASIC256}}==
===Iterative solution===
<
if m = 0 or n = 0 then return 0
if m < n then
Line 700 ⟶ 701:
print "lcm( 15, 12) = "; mcm( 15, 12)
print "lcm(-10, -14) = "; mcm(-10, -14)
print "lcm( 0, 1) = "; mcm( 0, 1)</
{{out}}
<pre>lcm( 12, 18) = 36
Line 710 ⟶ 711:
===Recursive solution===
Reuses code from Greatest_common_divisor#Recursive_solution and correctly handles negative arguments
<
if b = 0 then return a
return gcdp(b, a mod b)
Line 726 ⟶ 727:
print "lcm( 15, 12) = "; lcm( 15, 12)
print "lcm(-10, -14) = "; lcm(-10, -14)
print "lcm( 0, 1) = "; lcm( 0, 1)</
{{out}}
<pre>lcm( 12, -18) = 36.0
Line 734 ⟶ 735:
=={{header|Batch File}}==
<
setlocal enabledelayedexpansion
set num1=12
Line 751 ⟶ 752:
set /a res = %1 %% %2
call :lcm %2 %res%
goto :EOF</
{{Out}}
<pre>LCM = 36</pre>
Line 757 ⟶ 758:
=={{header|bc}}==
{{trans|AWK}}
<
define g(m, n) {
auto t
Line 778 ⟶ 779:
if (r < 0) return (-r)
return (r)
}</
=={{header|BCPL}}==
<
let lcm(m,n) =
Line 791 ⟶ 792:
gcd(n, m rem n)
let start() be writef("%N*N", lcm(12, 18))</
{{out}}
<pre>36</pre>
Line 799 ⟶ 800:
Inputs are limited to signed 16-bit integers.
<
>28*:*:**+:28*>:*:*/\:vv*-<
|<:%/*:*:*82\%*:*:*82<<>28v
>$/28*:*:*/*.@^82::+**:*:*<</
{{in}}
Line 812 ⟶ 813:
=={{header|BQN}}==
<
Example:
<syntaxhighlight lang
<pre>36</pre>
=={{header|Bracmat}}==
We utilize the fact that Bracmat simplifies fractions (using Euclid's algorithm). The function <code>den$<i>number</i></code> returns the denominator of a number.
<
a b
. !arg:(?a.?b)
Line 828 ⟶ 829:
* !a
);
out$(gcd$(12.18) gcd$(-6.14) gcd$(35.0) gcd$(117.18))</
Output:
<pre>36 42 35 234</pre>
=={{header|Brat}}==
<
gcd = { a, b |
true? { a == 0 }
Line 846 ⟶ 847:
p lcm(12, 18) # 36
p lcm(14, 21) # 42
</syntaxhighlight>
=={{header|Bruijn}}==
{{trans|Haskell}}
<syntaxhighlight lang="bruijn">
:import std/Math .
lcm [[=?1 1 (=?0 0 |(1 / (gcd 1 0) ⋅ 0))]]
:test ((lcm (+12) (+18)) =? (+36)) ([[1]])
:test ((lcm (+42) (+25)) =? (+1050)) ([[1]])
</syntaxhighlight>
=={{header|C}}==
<
int gcd(int m, int n)
Line 867 ⟶ 879:
printf("lcm(35, 21) = %d\n", lcm(21,35));
return 0;
}</
=={{header|C sharp|C#}}==
<
class Program
{
Line 886 ⟶ 898:
}
}
</syntaxhighlight>
{{out}}
<pre>lcm(12,18)=36</pre>
Line 892 ⟶ 904:
=={{header|C++}}==
{{libheader|Boost}}
<
#include <iostream>
Line 900 ⟶ 912:
<< "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ;
return 0 ;
}</
{{out}}
Line 909 ⟶ 921:
=== Alternate solution ===
{{works with|C++11}}
<
#include <cstdlib>
#include <iostream>
Line 934 ⟶ 946:
return 0;
}
</syntaxhighlight>
=={{header|Clojure}}==
<
[a b]
(if (zero? b)
Line 948 ⟶ 960:
;; to calculate the lcm for a variable number of arguments
(defn lcmv [& v] (reduce lcm v))
</syntaxhighlight>
=={{header|CLU}}==
<
m, n := int$abs(m), int$abs(n)
while n ~= 0 do m, n := n, m // n end
Line 967 ⟶ 979:
po: stream := stream$primary_output()
stream$putl(po, int$unparse(lcm(12, 18)))
end start_up</
{{out}}
<pre>36</pre>
=={{header|COBOL}}==
<
PROGRAM-ID. show-lcm.
Line 1,034 ⟶ 1,046:
GOBACK
.
END FUNCTION gcd.</
=={{header|Common Lisp}}==
Common Lisp provides the <tt>lcm</tt> function. It can accept two or more (or less) parameters.
<
36
CL-USER> (lcm 12 18 22)
396</
Here is one way to reimplement it.
<
(reduce (lambda (m n)
(cond ((or (= m 0) (= n 0)) 0)
Line 1,055 ⟶ 1,067:
36
CL-USER> (my-lcm 12 18 22)
396</
In this code, the <tt>lambda</tt> finds the least common multiple of two integers, and the <tt>reduce</tt> transforms it to accept any number of parameters. The <tt>reduce</tt> operation exploits how ''lcm'' is associative, <tt>(lcm a b c) == (lcm (lcm a b) c)</tt>; and how 1 is an identity, <tt>(lcm 1 a) == a</tt>.
=={{header|Cowgol}}==
<
sub gcd(m: uint32, n: uint32): (r: uint32) is
Line 1,080 ⟶ 1,092:
print_i32(lcm(12, 18));
print_nl();</
{{out}}
<pre>36</pre>
=={{header|D}}==
<
T gcd(T)(T a, T b) pure nothrow {
Line 1,106 ⟶ 1,118:
lcm("2562047788015215500854906332309589561".BigInt,
"6795454494268282920431565661684282819".BigInt).writeln;
}</
{{out}}
<pre>36
Line 1,112 ⟶ 1,124:
=={{header|Dart}}==
<
main() {
int x=8;
Line 1,129 ⟶ 1,141:
}
</syntaxhighlight>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Least_common_multiple#Pascal Pascal].
=={{header|DWScript}}==
<
Output:
<pre>36</pre>
=={{header|Draco}}==
<
word t;
while n /= 0 do
Line 1,158 ⟶ 1,170:
proc main() void:
writeln(lcm(12, 18))
corp</
{{out}}
<pre>36</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
func gcd a b .
while b <> 0
h = b
b = a mod b
a = h
.
return a
.
func lcm a b .
return a / gcd a b * b
.
print lcm 12 18
</syntaxhighlight>
{{out}}
<pre>
36
</pre>
=={{header|EchoLisp}}==
(lcm a b) is already here as a two arguments function. Use foldl to find the lcm of a list of numbers.
<
(lcm 0 9) → 0
(lcm 444 888)→ 888
Line 1,171 ⟶ 1,203:
(define (lcm* list) (foldl lcm (first list) list)) → lcm*
(lcm* '(444 888 999)) → 7992
</syntaxhighlight>
=={{header|Elena}}==
{{trans|C#}}
ELENA
<
import system'math;
gcd = (m,n => (n == 0) ? (m.Absolute) : (gcd(n,n.mod
lcm = (m,n => (m * n).Absolute / gcd(m,n));
Line 1,186 ⟶ 1,218:
{
console.printLine("lcm(12,18)=",lcm(12,18))
}</
{{out}}
<pre>
Line 1,193 ⟶ 1,225:
=={{header|Elixir}}==
<
def gcd(a,0), do: abs(a)
def gcd(a,b), do: gcd(b, rem(a,b))
Line 1,200 ⟶ 1,232:
end
IO.puts RC.lcm(-12,15)</
{{out}}
Line 1,208 ⟶ 1,240:
=={{header|Erlang}}==
<
-module(lcm).
-export([main/0]).
Line 1,222 ⟶ 1,254:
lcm(A,B) ->
abs(A*B div gcd(A,B)).</
{{out}}
Line 1,229 ⟶ 1,261:
=={{header|ERRE}}==
<
PROCEDURE GCD(A,B->GCD)
Line 1,258 ⟶ 1,290:
LCM(0,35->LCM)
PRINT("LCM of 0 AND 35 =";LCM)
END PROGRAM</
{{out}}
Line 1,265 ⟶ 1,297:
LCM of 0 and 35 = 0
</pre>
=={{header|Euler}}==
Note % is integer division in Euler, not the mod operator.
'''begin'''
'''new''' gcd; '''new''' lcm;
gcd <- ` '''formal''' a; '''formal''' b;
'''if''' b = 0 '''then''' a '''else''' gcd( b, a '''mod''' '''abs''' b )
'
;
lcm <- ` '''formal''' a; '''formal''' b;
'''abs''' [ a * b ] % gcd( a, b )
'
;
'''out''' lcm( 15, 20 )
'''end''' $
=={{header|Euphoria}}==
<
integer tmp
while m do
Line 1,279 ⟶ 1,328:
function lcm(integer m, integer n)
return m / gcd(m, n) * n
end function</
=={{header|Excel}}==
Excel's LCM can handle multiple values. Type in a cell:
<
This will get the LCM on the first 10 cells in the first row. Thus :
<pre>12 3 5 23 13 67 15 9 4 2
Line 1,290 ⟶ 1,339:
=={{header|Ezhil}}==
<
## இந்த நிரல் இரு எண்களுக்கு இடையிலான மீச்சிறு பொது மடங்கு (LCM), மீப்பெரு பொது வகுத்தி (GCD) என்ன என்று கணக்கிடும்
Line 1,347 ⟶ 1,396:
பதிப்பி "நீங்கள் தந்த இரு எண்களின் மீபொம (மீச்சிறு பொது மடங்கு, LCM) = ", மீபொம(அ, ஆ)
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
let lcm x y = x * y / (gcd x y)</
=={{header|Factor}}==
The vocabulary ''math.functions'' already provides ''lcm''.
<
26 28 lcm .</
This program outputs ''364''.
Line 1,364 ⟶ 1,413:
One can also reimplement ''lcm''.
<
IN: script
Line 1,375 ⟶ 1,424:
[ * abs ] [ gcd ] 2bi / ;
26 28 lcm .</
=={{header|Fermat}}==
<
=={{header|Forth}}==
<
begin dup while tuck mod repeat drop ;
: lcm ( a b -- n )
over 0= over 0= or if 2drop 0 exit then
2dup gcd abs */ ;</
=={{header|Fortran}}==
This solution is written as a combination of 2 functions, but a subroutine implementation would work great as well.
<syntaxhighlight lang="fortran">
integer function lcm(a,b)
integer:: a,b
Line 1,405 ⟶ 1,454:
gcd = abs(a)
end function gcd
</syntaxhighlight>
=={{header|FreeBASIC}}==
===Iterative solution===
<
Function lcm (m As Integer, n As Integer) As Integer
Line 1,426 ⟶ 1,475:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,437 ⟶ 1,486:
===Recursive solution===
Reuses code from [[Greatest_common_divisor#Recursive_solution]] and correctly handles negative arguments
<
if b = 0 then return a
return gcdp( b, a mod b )
Line 1,453 ⟶ 1,502:
print "lcm( 15, 12) = "; lcm(15, 12)
print "lcm(-10, -14) = "; lcm(-10, -14)
print "lcm( 0, 1) = "; lcm(0,1)</
{{out}}
Line 1,465 ⟶ 1,514:
=={{header|Frink}}==
Frink has a built-in LCM function that handles arbitrarily-large integers.
<
println[lcm[2562047788015215500854906332309589561, 6795454494268282920431565661684282819]]
</syntaxhighlight>
=={{header|FunL}}==
FunL has function <code>lcm</code> in module <code>integers</code> with the following definition:
<
lcm( _, 0 ) = 0
lcm( 0, _ ) = 0
lcm( x, y ) = abs( (x\gcd(x, y)) y )</
=={{header|GAP}}==
<
LcmInt(12, 18);
# 36</
=={{header|Go}}==
<
import (
Line 1,499 ⟶ 1,548:
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}</
{{out}}
<pre>
Line 1,506 ⟶ 1,555:
=={{header|Groovy}}==
<
gcd = { m, n -> m = m.abs(); n = n.abs(); n == 0 ? m : m%n == 0 ? n : gcd(n, m % n) }
Line 1,516 ⟶ 1,565:
println "LCD of $t.m, $t.n is $t.l"
assert lcd(t.m, t.n) == t.l
}</
{{out}}
<pre>LCD of 12, 18 is 36
Line 1,525 ⟶ 1,574:
{{trans|C}}
{{works with|PC-BASIC|any}}
<
10 PRINT "LCM(35, 21) = ";
20 LET MLCM = 35
Line 1,548 ⟶ 1,597:
450 LET GCD = NGCD
460 RETURN
</syntaxhighlight>
=={{header|Haskell}}==
Line 1,554 ⟶ 1,603:
That is already available as the function ''lcm'' in the Prelude. Here's the implementation:
<
lcm _ 0 = 0
lcm 0 _ = 0
lcm x y = abs ((x `quot` (gcd x y)) * y)</
=={{header|Icon}} and {{header|Unicon}}==
The lcm routine from the Icon Programming Library uses gcd. The routine is
<
procedure main()
write("lcm of 18, 36 = ",lcm(18,36))
write("lcm of 0, 9 = ",lcm(0,9))
end</
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/numbers.icn numbers provides lcm and gcd] and looks like this:
<
if (i = 0) | (j = 0) then return 0
return abs(i * j) / gcd(i, j)
end</
=={{header|J}}==
J provides the dyadic verb <code>*.</code> which returns the least common multiple of its left and right arguments.
<
36
12 *. 18 22
Line 1,588 ⟶ 1,637:
*./~ 0 1
0 0
0 1</
Note: least common multiple is the original boolean multiplication. Constraining the universe of values to 0 and 1 allows us to additionally define logical negation (and boolean algebra was redefined to include this constraint in the early 1900s - the original concept of boolean algebra is now known as a boolean ring (though, talking to some people: there's been some linguistic drift even there)).
=={{header|Java}}==
<
public class LCM{
Line 1,619 ⟶ 1,668:
System.out.println("lcm(" + m + ", " + n + ") = " + lcm);
}
}</
=={{header|JavaScript}}==
Line 1,630 ⟶ 1,679:
<math>\operatorname{lcm}(a_1,a_2,\ldots,a_n) = \operatorname{lcm}(\operatorname{lcm}(a_1,a_2,\ldots,a_{n-1}),a_n).</math>
<
{
var n = A.length, a = Math.abs(A[0]);
Line 1,643 ⟶ 1,692:
/* For example:
LCM([-50,25,-45,-18,90,447]) -> 67050
*/</
===ES6===
{{Trans|Haskell}}
<
'use strict';
Line 1,665 ⟶ 1,714:
return lcm(12, 18);
})();</
{{Out}}
Line 1,672 ⟶ 1,721:
=={{header|jq}}==
Direct method
<
def lcm(m; n):
def _lcm:
# state is [m, n, i]
if (.[2] % .[1]) == 0 then .[2] else (.[0:2] + [.[2] + m]) | _lcm end;
[m, n, m] | _lcm; </
=={{header|Julia}}==
Built-in function:
<syntaxhighlight lang
=={{header|K}}==
===K3===
{{works with|Kona}}
<syntaxhighlight lang="k"> gcd:{:[~x;y;_f[y;x!y]]}
lcm:{_abs _ x*y%gcd[x;y]}
lcm .'(12 18; -6 14; 35 0)
36 42 0
lcm/1+!20
232792560</syntaxhighlight>
===K6===
{{works with|ngn/k}}
<syntaxhighlight lang="k"> abs:|/-:\
gcd:{$[~x;y;o[x!y;x]]}
lcm:{abs[`i$x*y%gcd[x;y]]}
lcm .'(12 18; -6 14; 35 0)
36 42 0
lcm/1+!20
232792560</
=={{header|Klingphix}}==
<
abs int swap abs int swap
Line 1,709 ⟶ 1,769:
12 18 lcm print nl { 36 }
"End " input</
=={{header|Kotlin}}==
<
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
println(lcm(15, 9))
}
</syntaxhighlight>
=={{header|LabVIEW}}==
Line 1,723 ⟶ 1,783:
=={{header|Lasso}}==
<
while(#b != 0) => {
local(t = #b)
Line 1,741 ⟶ 1,801:
lcm(12, 18)
lcm(12, 22)
lcm(7, 31)</
{{out}}
<pre>42
Line 1,750 ⟶ 1,810:
=={{header|Liberty BASIC}}==
<
end
Line 1,765 ⟶ 1,825:
GCD = abs(a)
end function
</
=={{header|Logo}}==
<
output sqrt product :n :n
end
Line 1,778 ⟶ 1,838:
to lcm :m :n
output quotient (abs product :m :n) gcd :m :n
end</
Demo code:
<syntaxhighlight lang
Output:
Line 1,789 ⟶ 1,849:
=={{header|Lua}}==
<
while n ~= 0 do
local q = m
Line 1,802 ⟶ 1,862:
end
print( lcm(12,18) )</
=={{header|m4}}==
This should work with any POSIX-compliant m4. I have tested it with OpenBSD m4, GNU m4, and Heirloom Devtools m4.
<
define(`gcd',
Line 1,826 ⟶ 1,886:
lcm(12, 18) = 36
lcm(12, 22) = 132
lcm(7, 31) = 217</
{{out}}
Line 1,837 ⟶ 1,897:
=={{header|Maple}}==
The least common multiple of two integers is computed by the built-in procedure ilcm in Maple. This should not be confused with lcm, which computes the least common multiple of polynomials.
<
36
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
-> 36</
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang
=={{header|Maxima}}==
<
/* In Maxima the gcd of two integers is always positive, and a * b = gcd(a, b) * lcm(a, b),
so the lcm may be negative. To get a positive lcm, simply do */
abs(lcm(a, b))</
=={{header|Microsoft Small Basic}}==
{{trans|C}}
<
Textwindow.Write("LCM(35, 21) = ")
mlcm = 35
Line 1,881 ⟶ 1,941:
gcd = ngcd
EndSub
</syntaxhighlight>
=={{header|MiniScript}}==
<
while b
temp = b
Line 1,899 ⟶ 1,959:
print lcm(18,12)
</syntaxhighlight>
{{output}}
<pre>36</pre>
=={{header|MiniZinc}}==
<
let {
int:a1 = max(a2,b2);
Line 1,922 ⟶ 1,982:
var int: lcm1 = lcm(18,12);
solve satisfy;
output [show(lcm1),"\n"];</
{{output}}
<pre>36</pre>
=={{header|min}}==
{{works with|min|0.19.6}}
<
((dup 0 ==) (pop abs) (swap over mod) () linrec) :gcd
(over over gcd '* dip div) :lcm</
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">ИПA ИПB * |x| ПC ИПA ИПB / [x] П9
ИПA ИПB ПA ИП9 * - ПB x=0 05 ИПC
ИПA / С/П</
=={{header|ML}}==
==={{header|mLite}}===
<
| (0, b) = b
| (a, b) where (a < b)
Line 1,947 ⟶ 2,007:
in a * b div d
end
</syntaxhighlight>
=={{header|Modula-2}}==
{{trans|C}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<
MODULE LeastCommonMultiple;
Line 1,982 ⟶ 2,042:
WriteLn;
END LeastCommonMultiple.
</syntaxhighlight>
=={{header|Nanoquery}}==
<
if (a < 1) or (b < 1)
throw new(InvalidNumberException, "gcd cannot be calculated on values < 1")
Line 2,006 ⟶ 2,066:
println lcm(12, 18)
println lcm(6, 14)
println lcm(1,2) = lcm(2,1)</
{{out}}
Line 2,014 ⟶ 2,074:
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 2,084 ⟶ 2,144:
return
</syntaxhighlight>
{{out}}
<pre>
Line 2,109 ⟶ 2,169:
=={{header|Nim}}==
The standard module "math" provides a function "lcm" for two integers and for an open array of integers. If we absolutely want to compute the least common multiple with our own procedure, it can be done this way (less efficient than the function in the standard library which avoids the modulo):
<
var
u = u
Line 2,121 ⟶ 2,181:
echo lcm(12, 18)
echo lcm(-6, 14)</
{{out}}
Line 2,129 ⟶ 2,189:
=={{header|Objeck}}==
{{trans|C}}
<
class LCM {
function : Main(args : String[]) ~ Nil {
Line 2,145 ⟶ 2,205:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
<
if v <> 0 then (gcd v (u mod v))
else (abs u)
Line 2,159 ⟶ 2,219:
let () =
Printf.printf "lcm(35, 21) = %d\n" (lcm 21 35)</
=={{header|Oforth}}==
lcm is already defined into Integer class :
<syntaxhighlight lang
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
say lcm(18, 12)
Line 2,186 ⟶ 2,246:
use arg x, y
return x / gcd(x, y) * y
</syntaxhighlight>
=={{header|Order}}==
{{trans|bc}}
<
#define ORDER_PP_DEF_8gcd ORDER_PP_FN( \
Line 2,203 ⟶ 2,263:
// No support for negative numbers
ORDER_PP( 8to_lit(8lcm(12, 18)) ) // 36</
=={{header|PARI/GP}}==
Built-in function:
<syntaxhighlight lang
=={{header|Pascal}}==
<
{$IFDEF FPC}
Line 2,225 ⟶ 2,285:
begin
writeln('The least common multiple of 12 and 18 is: ', lcm(12, 18));
end.</
Output:
<pre>The least common multiple of 12 and 18 is: 36
Line 2,232 ⟶ 2,292:
=={{header|Perl}}==
Using GCD:
<
my ($x, $y) = @_;
while ($x) { ($x, $y) = ($y % $x, $x) }
Line 2,243 ⟶ 2,303:
}
print lcm(1001, 221);</
Or by repeatedly increasing the smaller of the two until LCM is reached:<
use integer;
my ($x, $y) = @_;
Line 2,256 ⟶ 2,316:
}
print lcm(1001, 221);</
=={{header|Phix}}==
It is a builtin function, defined in builtins\gcd.e and accepting either two numbers or a single sequence of any length.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">lcm</span><span style="color: #0000FF;">(</span><span style="color: #000000;">12</span><span style="color: #0000FF;">,</span><span style="color: #000000;">18</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">lcm</span><span style="color: #0000FF;">({</span><span style="color: #000000;">12</span><span style="color: #0000FF;">,</span><span style="color: #000000;">18</span><span style="color: #0000FF;">})</span>
<!--</
{{out}}
<pre>
Line 2,272 ⟶ 2,332:
=={{header|Phixmonti}}==
<
abs int swap abs int swap
Line 2,286 ⟶ 2,346:
enddef
12345 50 lcm print</
=={{header|PHP}}==
{{trans|D}}
<
function lcm($m, $n) {
Line 2,305 ⟶ 2,365:
}
return $a;
}</
=={{header|Picat}}==
Line 2,311 ⟶ 2,371:
===Function===
<
===Predicate===
<
===Functional (fold/3)===
<
===Test===
<
L = [
[12,18],
Line 2,335 ⟶ 2,395:
println('1..50'=lcm(1..50)),
nl.
</syntaxhighlight>
{{out}}
Line 2,348 ⟶ 2,408:
=={{header|PicoLisp}}==
Using 'gcd' from [[Greatest common divisor#PicoLisp]]:
<
(abs (*/ A B (gcd A B))) )</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
/* Calculate the Least Common Multiple of two integers. */
Line 2,377 ⟶ 2,437:
end GCD;
end LCM;
</syntaxhighlight>
<pre>
The LCM of 14 and 35 is 70
Line 2,384 ⟶ 2,444:
=={{header|PowerShell}}==
===version 1===
<syntaxhighlight lang="powershell">
function gcd ($a, $b) {
function pgcd ($n, $m) {
Line 2,401 ⟶ 2,461:
}
lcm 12 18
</syntaxhighlight>
===version 2===
version2 is faster than version1
<syntaxhighlight lang="powershell">
function gcd ($a, $b) {
function pgcd ($n, $m) {
Line 2,423 ⟶ 2,483:
}
lcm 12 18
</syntaxhighlight>
<b>Output:</b>
Line 2,432 ⟶ 2,492:
=={{header|Prolog}}==
SWI-Prolog knows gcd.
<
Z is abs(X * Y) / gcd(X,Y).</
Example:
Line 2,441 ⟶ 2,501:
=={{header|PureBasic}}==
<
Protected r
While b
Line 2,457 ⟶ 2,517:
EndIf
ProcedureReturn t*Sign(t)
EndProcedure</
=={{header|Python}}==
Line 2,463 ⟶ 2,523:
====gcd====
Using the fractions libraries [http://docs.python.org/library/fractions.html?highlight=fractions.gcd#fractions.gcd gcd] function:
<
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
Line 2,471 ⟶ 2,531:
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>> </
Or, for compositional flexibility, a curried '''lcm''', expressed in terms of our own '''gcd''' function:
<
from inspect import signature
Line 2,571 ⟶ 2,631:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Least common multiples of 60 and [12..20]:
Line 2,593 ⟶ 2,653:
====Prime decomposition====
This imports [[Prime decomposition#Python]]
<
try:
reduce
Line 2,614 ⟶ 2,674:
print( lcm(12, 18) ) # 36
print( lcm(-6, 14) ) # 42
assert lcm(0, 2) == lcm(2, 0) == 0</
====Iteration over multiples====
<
values = set([abs(int(v)) for v in values])
if values and 0 not in values:
Line 2,635 ⟶ 2,695:
>>> lcm(12, 18, 22)
396
>>> </
====Repeated modulo====
{{trans|Tcl}}
<
p, q = abs(p), abs(q)
m = p * q
Line 2,656 ⟶ 2,716:
>>> lcm(2, 0)
0
>>> </
=={{header|Qi}}==
<syntaxhighlight lang="qi">
(define gcd
A 0 -> A
Line 2,665 ⟶ 2,725:
(define lcm A B -> (/ (* A B) (gcd A B)))
</syntaxhighlight>
=={{header|Quackery}}==
<
tuck mod again ]
drop abs ] is gcd ( n n --> n )
Line 2,676 ⟶ 2,736:
[ 2dup gcd
/ * abs ]
else and ] is lcm ( n n --> n )</
=={{header|R}}==
<syntaxhighlight lang="r">
"%gcd%" <- function(u, v) {ifelse(u %% v != 0, v %gcd% (u%%v), v)}
Line 2,685 ⟶ 2,745:
print (50 %lcm% 75)
</syntaxhighlight>
=={{header|Racket}}==
Racket already has defined both lcm and gcd funtions:
<
(lcm 3 4 5 6) ;returns 60
(lcm 8 108) ;returns 216
(gcd 8 108) ;returns 4
(gcd 108 216 432) ;returns 108</
=={{header|Raku}}==
(formerly Perl 6)
This function is provided as an infix so that it can be used productively with various metaoperators.
<syntaxhighlight lang="raku"
say [lcm] 1..20; # reduction
say ~(1..10 Xlcm 1..10) # cross</
{{out}}
<pre>12
Line 2,709 ⟶ 2,769:
This is from the math extensions library included with Retro.
<
: lcm ( ab-n ) 2over gcd [ * ] dip / ;</
=={{header|REXX}}==
Line 2,719 ⟶ 2,779:
Usage note: the integers can be expressed as a list and/or specified as individual arguments (or as mixed).
<
numeric digits 10000 /*can handle 10k decimal digit numbers.*/
say 'the LCM of 19 and 0 is ───► ' lcm(19 0 )
Line 2,742 ⟶ 2,802:
x=d%x /*divide the pre─calculated value.*/
end /*while*/ /* [↑] process subsequent args. */
return x /*return with the LCM of the args.*/</
'''output''' when using the (internal) supplied list:
<pre>
Line 2,757 ⟶ 2,817:
{{trans|REXX version 0}} using different argument handling-
Use as lcm(a,b,c,---)
<
x=abs(arg(1))
do k=2 to arg() While x<>0
Line 2,777 ⟶ 2,837:
end
end
return x</
=={{header|Ring}}==
<syntaxhighlight lang="text">
see lcm(24,36)
Line 2,794 ⟶ 2,854:
end
return gcd
</syntaxhighlight>
=={{header|RPL}}==
'''For unsigned integers'''
≪ DUP2 < ≪ SWAP ≫ IFT
'''WHILE''' DUP B→R '''REPEAT'''
SWAP OVER / LAST ROT * - '''END''' DROP
≫ '<span style="color:blue">GCD</span>' STO
≪ DUP2 * ROT ROT <span style="color:blue">GCD</span> /
≫ '<span style="color:blue">LCM</span>' STO
#12d #18d <span style="color:blue">LCM</span>
{{out}}
<pre>
1: #36d
</pre>
'''For usual integers''' (floating point without decimal part)
≪ '''WHILE''' DUP '''REPEAT'''
SWAP OVER MOD '''END''' DROP ABS
≫ '<span style="color:blue">GCD</span>' STO
≪ DUP2 * ROT ROT <span style="color:blue">GCD</span> /
≫ '<span style="color:blue">LCM</span>' STO
=={{header|Ruby}}==
Ruby has an <tt>Integer#lcm</tt> method, which finds the least common multiple of two integers.
<
=> 36</
I can also write my own <tt>lcm</tt> method. This one takes any number of arguments.
<
m, n = n, m % n until n.zero?
m.abs
Line 2,817 ⟶ 2,900:
p lcm 12, 18, 22
p lcm 15, 14, -6, 10, 21</
{{out}}
Line 2,828 ⟶ 2,911:
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
<
print "lcm( 15, 12) = "; lcm( 15, 12)
print "lcm(-10, -14) = "; lcm(-10, -14)
Line 2,845 ⟶ 2,928:
wend
GCD = abs(a)
end function</
=={{header|Rust}}==
This implementation uses a recursive implementation of Stein's algorithm to calculate the gcd.
<
fn gcd(a: usize, b: usize) -> usize {
Line 2,871 ⟶ 2,954:
fn main() {
println!("{}", lcm(6324, 234))
}</
=={{header|Scala}}==
<
def lcm(a: Int, b: Int)=(a*b).abs/gcd(a,b)</
<
lcm( 2, 0) // 0
lcm(-6, 14) // 42</
=={{header|Scheme}}==
<
>(define gcd (lambda (a b)
(if (zero? b)
Line 2,891 ⟶ 2,974:
(abs (* b (floor (/ a (gcd a b))))))))
>(lcm 12 18)
36</
=={{header|Seed7}}==
<
const func integer: gcd (in var integer: a, in var integer: b) is func
Line 2,916 ⟶ 2,999:
begin
writeln("lcm(35, 21) = " <& lcm(21, 35));
end func;</
Original source: [http://seed7.sourceforge.net/algorith/math.htm#lcm]
=={{header|SenseTalk}}==
<
repeat while m is greater than 0
put m into temp
Line 2,932 ⟶ 3,015:
function lcm m, n
return m divided by gcd(m, n) times n
end lcm</
=={{header|Sidef}}==
Built-in:
<
Using GCD:
<
while (a) { (a, b) = (b % a, a) }
return b
Line 2,948 ⟶ 3,031:
}
say lcm(1001, 221)</
{{out}}
<pre>
Line 2,956 ⟶ 3,039:
=={{header|Smalltalk}}==
Smalltalk has a built-in <code>lcm</code> method on <code>SmallInteger</code>:
<syntaxhighlight lang
=={{header|Sparkling}}==
<
var f = {};
Line 2,991 ⟶ 3,074:
function LCM(n, k) {
return n * k / GCD(n, k);
}</
=={{header|Standard ML}}==
===Readable version===
<syntaxhighlight lang="sml">fun gcd (0,n) = n
| gcd (m,n) = gcd(n mod m, m)
fun lcm (m,n) = abs(x * y) div gcd (m, n)</syntaxhighlight>
===Alternate version===
<syntaxhighlight lang="sml">val rec gcd = fn (x, 0) => abs x | p as (_, y) => gcd (y, Int.rem p)
val lcm = fn p as (x, y) => Int.quot (abs (x * y), gcd p)</
=={{header|Swift}}==
Using the Swift GCD function.
<
return abs(a * b) / gcd_rec(a, b)
}</
=={{header|Tcl}}==
<
set m [expr {$p * $q}]
if {!$m} {return 0}
Line 3,014 ⟶ 3,104:
if {!$q} {return [expr {$m / $p}]}
}
}</
Demonstration
<syntaxhighlight lang
Output:
36
=={{header|TI-83 BASIC}}==
<
36</
=={{header|TSE SAL}}==
<
INTEGER PROC FNMathGetLeastCommonMultipleI( INTEGER x1I, INTEGER x2I )
//
Line 3,054 ⟶ 3,144:
Warn( FNMathGetLeastCommonMultipleI( Val( s1 ), Val( s2 ) ) ) // gives e.g. 10
UNTIL FALSE
END</
=={{header|TXR}}==
<
43259338018880832376582582128138484281161556655442781051813888</
== {{header|TypeScript}} ==
{{trans|C}}
<
function gcd(m: number, n: number): number {
Line 3,080 ⟶ 3,170:
console.log(`LCM(35, 21) = ${lcm(35, 21)}`);
</syntaxhighlight>
{{out}}
<pre>
Line 3,088 ⟶ 3,178:
=={{header|uBasic/4tH}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="text">Print "LCM of 12 : 18 = "; FUNC(_LCM(12,18))
End
Line 3,108 ⟶ 3,198:
Else
Return (0)
EndIf</
{{out}}
<pre>LCM of 12 : 18 = 36
Line 3,118 ⟶ 3,208:
{{works with|Bourne Shell}}
<
# Calculate $1 % $2 until $2 becomes zero.
until test 0 -eq "$2"; do
Line 3,138 ⟶ 3,228:
lcm 30 -42
# => 210</
==={{header|C Shell}}===
<
@ gcd_u=$gcd_args[2] \\
@ gcd_v=$gcd_args[3] \\
Line 3,164 ⟶ 3,254:
lcm result 30 -42
echo $result
# => 210</
=={{header|Ursa}}==
<
out (lcm 12 18) endl console</
{{out}}
<pre>36</pre>
=={{header|Vala}}==
<
int lcm(int a, int b){
/*Return least common multiple of two ints*/
Line 3,200 ⟶ 3,290:
stdout.printf("lcm(%d, %d) = %d\n", a, b, lcm(a, b));
}
</syntaxhighlight>
=={{header|VBA}}==
<
Dim t As Long
Do While v
Line 3,214 ⟶ 3,304:
Function lcm(m As Long, n As Long) As Long
lcm = Abs(m * n) / gcd(m, n)
End Function</
=={{header|VBScript}}==
<
LCM = POS((a * b)/GCD(a,b))
End Function
Line 3,246 ⟶ 3,336:
WScript.StdOut.Write "The LCM of " & i & " and " & j & " is " & LCM(i,j) & "."
WScript.StdOut.WriteLine</
{{out}}
Line 3,263 ⟶ 3,353:
=={{header|Wortel}}==
Operator
<syntaxhighlight lang
Number expression
<syntaxhighlight lang
Function (using gcd)
<
=={{header|Wren}}==
<
while (y != 0) {
var t = y
Line 3,287 ⟶ 3,377:
for (xy in xys) {
System.print("lcm(%(xy[0]), %(xy[1]))\t%("\b"*5) = %(lcm.call(xy[0], xy[1]))")
}</
{{out}}
Line 3,299 ⟶ 3,389:
{{trans|C}}
{{works with|Windows XBasic}}
<
PROGRAM "leastcommonmultiple"
VERSION "0.0001"
Line 3,325 ⟶ 3,415:
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 3,332 ⟶ 3,422:
=={{header|XPL0}}==
<
func GCD(M,N); \Return the greatest common divisor of M and N
Line 3,347 ⟶ 3,437:
\Display the LCM of two integers entered on command line
IntOut(0, LCM(IntIn(8), IntIn(8)))</
=={{header|Yabasic}}==
<
local t
Line 3,367 ⟶ 3,457:
end sub
print "Least common multiple: ", lcm(12345, 23044)</
=={{header|zkl}}==
<
{{out}}
<pre>
|