O menor múltiplo comum de um conjunto de números inteiros positivos A
é o menor número inteiro postive B
de tal modo que, para cada um k
no A
, existe um número inteiro positivo n
de tal modo que k*n = B
.
Dado pelo menos dois números inteiros positivos como entrada, produz o mínimo múltiplo comum.
Regras
- Builtins são permitidos, mas se sua solução usa um, recomendamos que você inclua uma solução alternativa que não use os built-in GCD / LCM. No entanto, a solução alternativa não conta para a sua pontuação, portanto é totalmente opcional.
- Todas as entradas e saídas estarão dentro do intervalo representável nativamente para o seu idioma. Se o seu idioma é capaz nativamente de números inteiros arbitrariamente grandes, sua solução deve funcionar com entradas e saídas arbitrariamente grandes.
Casos de teste
[7, 2] -> 14
[8, 1] -> 8
[6, 4, 8] -> 24
[8, 2, 1, 10] -> 40
[9, 6, 2, 1, 5] -> 90
[5, 5, 7, 1, 1] -> 35
[4, 13, 8, 8, 11, 1] -> 1144
[7, 2, 2, 11, 11, 8, 5] -> 3080
[1, 6, 10, 3, 4, 10, 7] -> 420
[5, 2, 9, 10, 3, 4, 4, 4, 7] -> 1260
[9, 7, 10, 9, 7, 8, 5, 10, 1] -> 2520
Respostas:
Na verdade,
121 byteSugestões de golfe ainda são bem-vindas, embora eu não tenha certeza de como melhorar o LCM bruto incorporado. Experimente online!
A 12-byte version without the built-in. Golfing suggestions welcome. Try it online!
Ungolfing
fonte
JavaScript (ES6), 36 bytes
Starting from
1
it's the first number that can be divided by all.Show code snippet
fonte
some
returns true if at least one element in the array satisfies the condition, right?05AB1E/2sable, 2 bytes
Try it online! in 05AB1E
or 2sable
fonte
Jelly, 3 bytes
Reduces by LCM. Try it online! or verify all test cases.
Alternate version, 6 bytes
Try it online! or verify all test cases.
How it works
fonte
Python,
69655250 bytes2 bytes saved thanks to Dennis!
Pretty straightforward recursive solution, you will need to make the recursion limit a bit higher for some of the test cases to work.
fonte
any
takes a generator; you don't need the brackets.A=lambda l,i=1:all(i%a<1for a in l)or-~A(l,i+1)
saves a few more bytes.MATL, 7 bytes
No builtin.
Try it online!
Explanation
Let's take input
[8, 2, 1, 10]
as an example.EDIT (June 9, 2017):
YF
with two outputs has been modified in release 20.1.0: non-factor primes and their (zero) exponents are skipped. This doesn't affect the above code, which works without requiring any changes.fonte
Julia (3 Bytes) [Working on Non-Built-in]
As Dennis pointed out, I keep forgetting that Julia automatically vectorizes inputs.
Example:
fonte
PowerShell v2+,
7360 bytesTakes input
$a
, loops upward from$i=1
with$i++
, based on a conditional. The condition is($a|?{!($i%$_)}).count
being-n
ote
qual to$a.count
. Meaning, the loop ends when the elements of$a
that are divisors of$i
is equal to the elements of$a
. Then, a solitary$i
is left on the pipeline, and output is implicit.Test Cases
fonte
Mathematica, 3 bytes
Usage:
fonte
Cheddar, 33 bytes
Nothing super new.
Ungolfed
Basically this starts at one and keeps increasing until it finds an LCM
fonte
JavaScript (ES6),
6359 bytesRecursively finds the LCM of the last two elements.
fonte
a=>a.reduce((l,n)=>l*n/(g=(m,n)=>n?g(n,m%n):m)(l,n))
Dyalog APL, 2 bytes
Reduces by LCM. Test it on TryAPL.
fonte
JavaScript (ES6), 52 bytes
I
reduce
d this answer as much as I could but I'm obviously not going to get anywhere near the simplicity of @Hedi's answer.fonte
Java 8,
755912189 bytesUses the Euclidean Algorithm and the fact that LCM(A, B)= A * B / GCD(A, B)
Code:
Remove line-breaks:
fonte
n->{...}
I believe it becomes valid Java 8.int g(int a,int b){return b<1?a:g(b,a%b);}
. LCM can then becomeint l(int[]a){int l=1;for(int n:a)l=l*n/g(l,n);return l;}
, for a total of 99 bytes.MATL, 3 bytes
This uses the builtin function with array input.
Try it online!
fonte
Brachylog, 17 bytes
Try it online!
Explanation
fonte
Perl 6, 10 bytes
basically the same as:
fonte
J, 11 bytes
There is a solution for 3 bytes using the LCM builtin.
Explanation
fonte
CJam,
181716 bytes1 byte saved thanks to Martin Ender.
Incrementing until the LCM is found.
Try it online
fonte
Racket 13 bytes
lcm is a built-in function in Racket:
Testing:
Output:
fonte
R, 36 bytes (not builtin)
Takes the input. Then tests each positive integer by taking the mod.
fonte
cat
around your lasti
ec=T
is fine for +4 rather than +5 forcat()
.v=scan();while(any((F=F+1)%%v)){};F
withcat()
orec=T
making it 40 or 39 bytes, respectively. And +1, very nice approach.Pyth, 9 bytes
A program that takes input of a list on STDIN and prints the result.
Try it online or verify all test cases
How it works
fonte
Haskell, 10 bytes
Usage example:
foldl1 lcm [5,2,9,10,3,4,4,4,7]
->1260
.fonte
C#, 50+18 = 68 bytes
50 bytes for method defintion, +18 bytes for LINQ import.
Pretty much the same as a lot of other answers. Counts up recursively until it finds the LCM. I was a bit surprised this didn't get a StackOverflowException, so I also have a non-recursive version which is actually just 1 byte longer.
Ungolfed:
fonte
Pip, 10 bytes
Uses the "try every number until one works" strategy. Try it online!
fonte
PHP,
4274 bytesstraight forward:
loop
$f
from 1 upwards; if$f*$a
divides through$b
without a remainder, the LCM is found.I totally had overread the
at least
... here´s the code for any number of parameters:Loop
$f
from 1 upwards while inner loop has not run to $argc.Loop
$i
from2
to$argc-1
while$f*$argv[1]
divides through$argv[$i]
without a remainder.both loops broken: print
$f*$argument 1
.fonte
Prolog (SWI), 46 bytes
Try it online!
Another solution, 59 bytes:
fonte
Python 3, 83 bytes
fonte
Brachylog v2, 8 bytes
Try it online!
It's funny just how directly this maps on to the definition given in the challenge.
A suspiciously slow but significantly shorter solution:
Brachylog v2, 5 bytes
Try it online!
Takes input through the output variable and gives output through the input variable. Rips right through the first four test cases but I'm still waiting on the fifth... Ordinarily, I'd still make it my primary solution and just trust that it works correctly, but I don't know why it hasn't confirmed that 90 is the LCM of
9, 6, 2, 1, 5
when I gave it 90 twenty minutes ago.(Edit: It confirmed the answer after no more than 16 hours, and generated it alongside the LCM of
5, 5, 7, 1, 1
after about two days.)And another completely different predicate that accidentally more-or-less translates Fatalize's Brachylog v1 solution:
Brachylog v2, 10 bytes
Try it online!
This was salvaged from a solution I'd made for this challenge before I realized the output wasn't restricted to being an integer.
fonte
Pyth -
76 bytesNo builtin.
Try it online here.
fonte
[4]
, or anything else with a repeated prime factor.