Desafio
É simples: dado um número inteiro positivo de até 1.000.000, retorne o número primo mais próximo.
Se o número em si é primo, você deve retornar esse número; se houver dois números primos igualmente próximos ao número fornecido, retorne o menor dos dois.
A entrada está na forma de um único número inteiro e a saída também deve estar na forma de um número inteiro.
Não me importo com o modo como você recebe a entrada (função, STDIN, etc.) ou exibe a saída (função, STDOUT, etc.), desde que funcione.
Este é um código de golfe, portanto, aplicam-se regras padrão - o programa com menos bytes vence!
Casos de teste
Input => Output
------ -------
80 => 79
100 => 101
5 => 5
9 => 7
532 => 523
1 => 2
Respostas:
Gaia, 3 bytes
Try it online!
Rather slow for large inputs, but works given enough memory/time.
I'm not sure why
D⌡
implicitly pushesz
again, but it makes this a remarkably short answer!fonte
JavaScript (ES6), 53 bytes
Try it online!
Commented
fonte
05AB1E, 5 bytes
Try it online! or as a Test Suite
Inefficient for big numbers
fonte
Ån
is "In case of a tie, the higher prime is pushed" Didn't even knew we had this builtin, tbh.Octave, 40 bytes
Try it online!
This uses the fact that there is always a prime between
n
and2*n
(Bertrand–Chebyshev theorem).How it works
fonte
Japt, 5 bytes
Try it or run all test cases
fonte
05AB1E, 4 bytes
Try it online!
fonte
Wolfram Language (Mathematica), 31 bytes
Try it online!
1000003 is the 78499th prime.
Nearest
prioritizes values which appear earlier in the list (which are lower).fonte
Nearest[Prime@Range@#,#,1]&
for 27Brachylog,
75 bytesTry it online!
Saved 2 bytes thanks to @DLosc.
Explanation
fonte
≜
from the start, I assume, whereas I was thinking about pairing and subtracting and only later realized I'd need≜
to make it work. :)Pyth, 10 bytes
Try it online here, or verify all the test cases at once here.
fonte
Jelly,
97 bytesTry it online!
Slow for larger input, but works ok for the requested range. Thanks to @EriktheOutgolfer for saving 2 bytes!
fonte
_A¥
withạ
(absolute difference). Oh, andḤ
can really be‘
.‘
won’t always work? It means that only primes up to n+1 will be found, while the closest might be n+2.Python 2, 71 bytes
Try it online!
A recursive function that uses the Wilson's Theorem prime generator. The product(k−1)!2 , and
p
tracksp%k
is 1 for primes and 0 for non-primes. To make it easy to compareabs(k-n)
for different primesk
, we storek-n
and compare viaabs
, adding backn
to get the resultk
.The expression
k+n-p%k*2*n
is designed to givek-n
on primes (wherep%k=1
), and otherwise a "bad" value ofk+n
that's always bigger in absolute value and so doesn't affect the minimum, so that non-primes are passed over.fonte
C (gcc),
87767472 bytesOptimization of innat3's C# (Visual C# Interactive Compiler), 100 bytes
Try it online!
fonte
r!=2
is equivalent tor-2
,n%++i?0:r++
can most likely ben%++i||r++
.Tidy, 43 bytes
Try it online!
Explanation
This is a lambda with parameter
x
. This works by creating the following sequence:This is splicing together the two sequences
]x, -1, -∞]
(left-closed, right-open) and[x, ∞]
(both open).For
x = 80
, this looks like:Then, we use
f↦s
to select all elements froms
satisfyingf
. In this case, we filter out all composite numbers, leaving only the prime ones. For the samex
, this becomes:Then, we use
(...)@0
to select the first member of this sequence. Since the lower of the two needs to be selected, the sequence which starts withx - 1
is spliced in first.Note: Only one of
x
andx - 1
can be prime, so it is okay that the spliced sequence starts withx - 1
. Though the sequence could be open on both sides ([x,-1,-∞]
), this would needlessly includex
twice in the sequence. So, for sake of "efficiency", I chose the left-closed version (also because I like to show off Tidy).fonte
Factor, 91 bytes
Try it online!
fonte
APL (Dyalog Extended),
2015 bytesSBCSTacit prefix function inspired by Galen Ivanov's J answer.
Try it online!
⍳
ɩndices one through the argument.¯2⍭
nth primes of that⊢(
…)
apply the following tacit function to that, with the original argument as left argument:⊢
the primes⊇
indexed by:⍋
the ascending grade (indices which would sort ascending)⍤
of|
the magnitude (absolute value)⍤
of-
the differences⊃
pick the first one (i.e. the one with smallest difference)fonte
Perl 6, 35 bytes
Try it online!
This uses Veitcel's technique for generating the list of
0, -1, 2, -3
but simplifies it greatly to($*=-1)*$++
using the anonymous state variables available in P6 (I originally had-1 ** $++ * $++
, but when golfed the negative loses precedence). There's a built in prime checker but unfortunately theuntil
prevents the automagically returned value so there's an extra$_
hanging around.fonte
C,
122121104 bytesUse it calling function
c()
and passing as argument the number; it should return the closest prime.Thanks to Embodiment of Ignorance for
1 byte saveda big improvement.Try it online!
fonte
c()
receives two parameters... Also, you can probably shorten thewhile(1)
tofor(;;)
(untested, since I don't get how to run your codec()
passing only the first parameter. And you are right,for(;;)
saves me a byte, only 117 left to get first place :)#define r return p(a,i){i=1;while(++i<a)if(a%i<1)r 0;r a>1;}c(a,b){b=a;for(;;b++){if(p(--a))r a;if(p(b))r b;}}
. Here is a TIO link: tio.run/…Wolfram Language (Mathematica), 52 bytes
Try it online!
fonte
APL(NARS), 38 chars, 76 bytes
0π is the test for prime, ¯1π the prev prime, 1π is the next prime; test:
fonte
J,
1915 bytesTry it online!
fonte
Perl 5, 59 bytes
Try it online!
/^.?$|^(..+?)\1+$/
is tricky regexp to check prime(-1)**$a*($a++)
generate sequence 0,-1, 2,-3 ...fonte
MathGolf, 10 bytes
Try it online.
Explanation:
fonte
Python 2 (Cython), 96 bytes
Try it online!
fonte
r=range;...
C# (Visual C# Interactive Compiler),
104100 bytesTry it online!
Explanation:
fonte
Java 8,
8887 bytesPort of @NaturalNumberGuy's (first) C answer, so make sure to upvote him!!
-1 byte thanks to @OlivierGrégoire.
Try it online.
Explanation:
fonte
Java (JDK), 103 bytes
Try it online!
fonte
;
. :) Do you want me to delete my answer?.. Feel free to copy the explanation.Haskell,
7974 bytes (thanks to Laikoni)72 bytes as annonymus function (the initial "f=" could be removed in this case).
Try it online!
original code:
Try it online!
Explanation:
fonte
,
instead of&&
.(last$ ...)
can belast(...)
, and the second guard1>0
can be used for a binding to save parenthesis, e.g.y<-x+n
.f=
does not need to be counted. Also the parenthesis enclosing(-1+n)
can be dropped.VDM-SL, 161 bytes
A full program to run might look like this - it's worth noting that the bounds of the set of primes used should probably be changed if you actually want to run this, since it will take a long time to run for 1 million:
Explanation:
fonte
MATL, 6 bytes
Try it online!
List the first
n
primes and find the one closest ton
.fonte
C# (Visual C# Interactive Compiler), 112 bytes
Try it online!
Left shifts by 20 in submission but 10 in TIO so that TIO terminates for test cases.
fonte