Return the Closest Prime Number












32












$begingroup$


Challenge



This is a simple one: Given a positive integer up to 1,000,000, return the closest prime number.



If the number itself is prime, then you should return that number; if there are two primes equally close to the provided number, return the lower of the two.



Input is in the form of a single integer, and output should be in the form of an integer as well.



I don't care how you take in the input (function, STDIN, etc.) or display the output (function, STDOUT, etc.), as long as it works.



This is code golf, so standard rules apply—the program with the least bytes wins!



Test Cases



Input  =>  Output
------ -------
80 => 79
100 => 101
5 => 5
9 => 7
532 => 523
1 => 2









share|improve this question











$endgroup$








  • 5




    $begingroup$
    Hi and welcome to PPCG!. To avoid down voting due to lack of quality I suggest you to post it to the sandbox first and after a couple of days post it here
    $endgroup$
    – Luis felipe De jesus Munoz
    Mar 27 at 15:17










  • $begingroup$
    This is one of the outputs requested in this challenge.
    $endgroup$
    – Arnauld
    Mar 27 at 15:24










  • $begingroup$
    Very closely related but not quite identical.
    $endgroup$
    – Giuseppe
    Mar 27 at 15:35










  • $begingroup$
    @Arnauld I saw that one, but I thought that they were different enough to warrant a new question.
    $endgroup$
    – Nathan Dimmer
    Mar 27 at 15:37






  • 2




    $begingroup$
    See also OEIS A051697.
    $endgroup$
    – Eric Towers
    Mar 28 at 8:52
















32












$begingroup$


Challenge



This is a simple one: Given a positive integer up to 1,000,000, return the closest prime number.



If the number itself is prime, then you should return that number; if there are two primes equally close to the provided number, return the lower of the two.



Input is in the form of a single integer, and output should be in the form of an integer as well.



I don't care how you take in the input (function, STDIN, etc.) or display the output (function, STDOUT, etc.), as long as it works.



This is code golf, so standard rules apply—the program with the least bytes wins!



Test Cases



Input  =>  Output
------ -------
80 => 79
100 => 101
5 => 5
9 => 7
532 => 523
1 => 2









share|improve this question











$endgroup$








  • 5




    $begingroup$
    Hi and welcome to PPCG!. To avoid down voting due to lack of quality I suggest you to post it to the sandbox first and after a couple of days post it here
    $endgroup$
    – Luis felipe De jesus Munoz
    Mar 27 at 15:17










  • $begingroup$
    This is one of the outputs requested in this challenge.
    $endgroup$
    – Arnauld
    Mar 27 at 15:24










  • $begingroup$
    Very closely related but not quite identical.
    $endgroup$
    – Giuseppe
    Mar 27 at 15:35










  • $begingroup$
    @Arnauld I saw that one, but I thought that they were different enough to warrant a new question.
    $endgroup$
    – Nathan Dimmer
    Mar 27 at 15:37






  • 2




    $begingroup$
    See also OEIS A051697.
    $endgroup$
    – Eric Towers
    Mar 28 at 8:52














32












32








32


5



$begingroup$


Challenge



This is a simple one: Given a positive integer up to 1,000,000, return the closest prime number.



If the number itself is prime, then you should return that number; if there are two primes equally close to the provided number, return the lower of the two.



Input is in the form of a single integer, and output should be in the form of an integer as well.



I don't care how you take in the input (function, STDIN, etc.) or display the output (function, STDOUT, etc.), as long as it works.



This is code golf, so standard rules apply—the program with the least bytes wins!



Test Cases



Input  =>  Output
------ -------
80 => 79
100 => 101
5 => 5
9 => 7
532 => 523
1 => 2









share|improve this question











$endgroup$




Challenge



This is a simple one: Given a positive integer up to 1,000,000, return the closest prime number.



If the number itself is prime, then you should return that number; if there are two primes equally close to the provided number, return the lower of the two.



Input is in the form of a single integer, and output should be in the form of an integer as well.



I don't care how you take in the input (function, STDIN, etc.) or display the output (function, STDOUT, etc.), as long as it works.



This is code golf, so standard rules apply—the program with the least bytes wins!



Test Cases



Input  =>  Output
------ -------
80 => 79
100 => 101
5 => 5
9 => 7
532 => 523
1 => 2






code-golf primes






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 17:17









Toby Speight

4,49711535




4,49711535










asked Mar 27 at 15:16









Nathan DimmerNathan Dimmer

331311




331311








  • 5




    $begingroup$
    Hi and welcome to PPCG!. To avoid down voting due to lack of quality I suggest you to post it to the sandbox first and after a couple of days post it here
    $endgroup$
    – Luis felipe De jesus Munoz
    Mar 27 at 15:17










  • $begingroup$
    This is one of the outputs requested in this challenge.
    $endgroup$
    – Arnauld
    Mar 27 at 15:24










  • $begingroup$
    Very closely related but not quite identical.
    $endgroup$
    – Giuseppe
    Mar 27 at 15:35










  • $begingroup$
    @Arnauld I saw that one, but I thought that they were different enough to warrant a new question.
    $endgroup$
    – Nathan Dimmer
    Mar 27 at 15:37






  • 2




    $begingroup$
    See also OEIS A051697.
    $endgroup$
    – Eric Towers
    Mar 28 at 8:52














  • 5




    $begingroup$
    Hi and welcome to PPCG!. To avoid down voting due to lack of quality I suggest you to post it to the sandbox first and after a couple of days post it here
    $endgroup$
    – Luis felipe De jesus Munoz
    Mar 27 at 15:17










  • $begingroup$
    This is one of the outputs requested in this challenge.
    $endgroup$
    – Arnauld
    Mar 27 at 15:24










  • $begingroup$
    Very closely related but not quite identical.
    $endgroup$
    – Giuseppe
    Mar 27 at 15:35










  • $begingroup$
    @Arnauld I saw that one, but I thought that they were different enough to warrant a new question.
    $endgroup$
    – Nathan Dimmer
    Mar 27 at 15:37






  • 2




    $begingroup$
    See also OEIS A051697.
    $endgroup$
    – Eric Towers
    Mar 28 at 8:52








5




5




$begingroup$
Hi and welcome to PPCG!. To avoid down voting due to lack of quality I suggest you to post it to the sandbox first and after a couple of days post it here
$endgroup$
– Luis felipe De jesus Munoz
Mar 27 at 15:17




$begingroup$
Hi and welcome to PPCG!. To avoid down voting due to lack of quality I suggest you to post it to the sandbox first and after a couple of days post it here
$endgroup$
– Luis felipe De jesus Munoz
Mar 27 at 15:17












$begingroup$
This is one of the outputs requested in this challenge.
$endgroup$
– Arnauld
Mar 27 at 15:24




$begingroup$
This is one of the outputs requested in this challenge.
$endgroup$
– Arnauld
Mar 27 at 15:24












$begingroup$
Very closely related but not quite identical.
$endgroup$
– Giuseppe
Mar 27 at 15:35




$begingroup$
Very closely related but not quite identical.
$endgroup$
– Giuseppe
Mar 27 at 15:35












$begingroup$
@Arnauld I saw that one, but I thought that they were different enough to warrant a new question.
$endgroup$
– Nathan Dimmer
Mar 27 at 15:37




$begingroup$
@Arnauld I saw that one, but I thought that they were different enough to warrant a new question.
$endgroup$
– Nathan Dimmer
Mar 27 at 15:37




2




2




$begingroup$
See also OEIS A051697.
$endgroup$
– Eric Towers
Mar 28 at 8:52




$begingroup$
See also OEIS A051697.
$endgroup$
– Eric Towers
Mar 28 at 8:52










37 Answers
37






active

oldest

votes













1 2
next












12












$begingroup$

JavaScript (ES6), 53 bytes





n=>(g=(o,d=N=n+o)=>N%--d?g(o,d):d-1?g(o<0?-o:~o):N)``


Try it online!



Commented



n => (            // n = input
g = ( // g = recursive function taking:
o, // o = offset
d = // d = current divisor, initialized to N
N = n + o // N = input + offset
) => //
N % --d ? // decrement d; if d is not a divisor of N:
g(o, d) // do recursive calls until it is
: // else:
d - 1 ? // if d is not equal to 1 (either N is composite or N = 1):
g( // do a recursive call with the next offset:
o < 0 ? // if o is negative:
-o // make it positive (e.g. -1 -> +1)
: // else:
~o // use -(o + 1) (e.g. +1 -> -2)
) // end of recursive call
: // else (N is prime):
N // stop recursion and return N
)`` // initial call to g with o = [''] (zero-ish)





share|improve this answer











$endgroup$





















    10












    $begingroup$


    05AB1E, 5 bytes



    Åps.x


    Try it online!
    or as a Test Suite



    Inefficient for big numbers






    share|improve this answer









    $endgroup$









    • 2




      $begingroup$
      Too bad Ån is "In case of a tie, the higher prime is pushed" Didn't even knew we had this builtin, tbh.
      $endgroup$
      – Kevin Cruijssen
      Mar 28 at 7:51










    • $begingroup$
      @KevinCruijssen: Neither did I until now :)
      $endgroup$
      – Emigna
      Mar 28 at 9:15



















    7












    $begingroup$


    Gaia, 3 bytes



    ṅD⌡


    Try it online!



    Rather slow for large inputs, but works given enough memory/time.



    I'm not sure why D⌡ implicitly pushes z again, but it makes this a remarkably short answer!



    ṅ	| implicit input z: push first z prime numbers, call it P
    D⌡ | take the absolute difference between P and (implicit) z,
    | returning the smallest value in P with the minimum absolute difference





    share|improve this answer











    $endgroup$





















      7












      $begingroup$


      Octave, 40 bytes





      @(n)p([~,k]=min(abs(n-(p=primes(2*n)))))


      Try it online!



      This uses the fact that there is always a prime between n and 2*n (Bertrand–Chebyshev theorem).



      How it works



      @(n)p([~,k]=min(abs(n-(p=primes(2*n)))))

      @(n) % Define anonymous function with input n
      p=primes(2*n) % Vector of primes up to 2*n. Assign to p
      abs(n-( )) % Absolute difference between n and each prime
      [~,k]=min( ) % Index of first minimum (assign to k; not used)
      p( ) % Apply that index to p





      share|improve this answer











      $endgroup$





















        6












        $begingroup$


        Japt, 5 bytes



        _j}cU


        Try it or run all test cases



        _j}cU     :Implicit input of integer U
        _ :Function taking an integer as an argument
        j : Test if integer is prime
        } :End function
        cU :Return the first integer in [U,U-1,U+1,U-2,...] that returns true





        share|improve this answer











        $endgroup$





















          5












          $begingroup$


          05AB1E, 4 bytes



          z-Ån


          Try it online!






          share|improve this answer









          $endgroup$





















            4












            $begingroup$

            Pyth, 10 bytes



            haDQfP_TSy


            Try it online here, or verify all the test cases at once here.



            haDQfP_TSyQ   Implicit: Q=eval(input())
            Trailing Q inferred
            yQ 2 * Q
            S Range from 1 to the above
            f Filter keep the elements of the above, as T, where:
            P_T Is T prime?
            D Order the above by...
            a Q ... absolute difference between each element and Q
            This is a stable sort, so smaller primes will be sorted before larger ones if difference is the same
            h Take the first element of the above, implicit print





            share|improve this answer









            $endgroup$





















              4












              $begingroup$


              Jelly, 9 7 bytes



              ḤÆRạÞµḢ


              Try it online!



              Slow for larger input, but works ok for the requested range. Thanks to @EriktheOutgolfer for saving 2 bytes!






              share|improve this answer











              $endgroup$













              • $begingroup$
                Hey, that's clever! Save two by substituting _A¥ with (absolute difference). Oh, and can really be .
                $endgroup$
                – Erik the Outgolfer
                Mar 27 at 19:08












              • $begingroup$
                @EriktheOutgolfer thanks. Surely using won’t always work? It means that only primes up to n+1 will be found, while the closest might be n+2.
                $endgroup$
                – Nick Kennedy
                Mar 27 at 22:39










              • $begingroup$
                Hm, that's a concern.
                $endgroup$
                – Erik the Outgolfer
                Mar 27 at 22:40





















              4












              $begingroup$


              Wolfram Language (Mathematica), 31 bytes



              Nearest[Prime~Array~78499,#,1]&


              Try it online!



                                            & (*pure function*)
              Prime~Array~78499 (*among the (ascending) first 78499 primes*)
              1 (*select one*)
              Nearest[ ,#, ] (*which is nearest to the argument*)


              1000003 is the 78499th prime. Nearest prioritizes values which appear earlier in the list (which are lower).






              share|improve this answer











              $endgroup$









              • 4




                $begingroup$
                Nearest[Prime@Range@#,#,1]& for 27
                $endgroup$
                – Ben
                Mar 29 at 16:10



















              4












              $begingroup$


              Brachylog, 7 5 bytes



              ;I≜-ṗ


              Try it online!



              Saved 2 bytes thanks to @DLosc.



              Explanation



              ;I≜      Label an unknown integer I (tries 0, then 1, then -1, then 2, etc.)
              - Subtract I from the input
              ṗ The result must be prime





              share|improve this answer











              $endgroup$













              • $begingroup$
                @DLosc Mostly because I am stupid. Thanks.
                $endgroup$
                – Fatalize
                Mar 29 at 8:26










              • $begingroup$
                I think we just approached it from different directions. You were thinking about from the start, I assume, whereas I was thinking about pairing and subtracting and only later realized I'd need to make it work. :)
                $endgroup$
                – DLosc
                Mar 29 at 21:27



















              4












              $begingroup$


              C (gcc), 87 76 74 72 bytes



              Optimization of innat3's C# (Visual C# Interactive Compiler), 100 bytes



              f(n,i,t,r,m){for(t=0,m=n;r-2;t++)for(r=i=1,n+=n<m?t:-t;i<n;n%++i||r++);}


              Try it online!






              share|improve this answer











              $endgroup$













              • $begingroup$
                Hello and welcome to PPCG. A few tips: r!=2 is equivalent to r-2, n%++i?0:r++ can most likely be n%++i||r++.
                $endgroup$
                – Jonathan Frech
                Mar 29 at 13:11










              • $begingroup$
                I didn't immediately see that. Thanks.
                $endgroup$
                – Natural Number Guy
                Mar 29 at 15:13



















              3












              $begingroup$


              Tidy, 43 bytes



              {x:(prime↦splice(]x,-1,-∞],[x,∞]))@0}


              Try it online!



              Explanation



              This is a lambda with parameter x. This works by creating the following sequence:



              [x - 1, x, x - 2, x + 1, x - 3, x + 2, x - 4, x + 3, ...]


              This is splicing together the two sequences ]x, -1, -∞] (left-closed, right-open) and [x, ∞] (both open).



              For x = 80, this looks like:



              [79, 80, 78, 81, 77, 82, 76, 83, 75, 84, 74, 85, ...]


              Then, we use f↦s to select all elements from s satisfying f. In this case, we filter out all composite numbers, leaving only the prime ones. For the same x, this becomes:



              [79, 83, 73, 71, 89, 67, 97, 61, 59, 101, 103, 53, ...]


              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 with x - 1 is spliced in first.



              Note: Only one of x and x - 1 can be prime, so it is okay that the spliced sequence starts with x - 1. Though the sequence could be open on both sides ([x,-1,-∞]), this would needlessly include x twice in the sequence. So, for sake of "efficiency", I chose the left-closed version (also because I like to show off Tidy).






              share|improve this answer









              $endgroup$





















                3












                $begingroup$


                Python 2, 71 bytes





                f=lambda n,k=1,p=1:k<n*3and min(k+n-p%k*2*n,f(n,k+1,p*k*k)-n,key=abs)+n


                Try it online!



                A recursive function that uses the Wilson's Theorem prime generator. The product p tracks $(k-1)!^2$, and p%k is 1 for primes and 0 for non-primes. To make it easy to compare abs(k-n) for different primes k, we store k-n and compare via abs, adding back n to get the result k.



                The expression k+n-p%k*2*n is designed to give k-n on primes (where p%k=1), and otherwise a "bad" value of k+n that's always bigger in absolute value and so doesn't affect the minimum, so that non-primes are passed over.






                share|improve this answer









                $endgroup$





















                  3












                  $begingroup$


                  APL (Dyalog Extended), 20 15 bytesSBCS





                  Tacit prefix function inspired by Galen Ivanov's J answer.



                  ⊢(⊃⍋⍤|⍤-⊇⊢)¯2⍭⍳


                  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)






                  share|improve this answer











                  $endgroup$





















                    3












                    $begingroup$


                    Perl 6, 35 bytes





                    {$_+=($*=-1)*$++until .is-prime;$_}


                    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 the until prevents the automagically returned value so there's an extra $_ hanging around.






                    share|improve this answer











                    $endgroup$













                    • $begingroup$
                      I'd usually use a sequence operator approach to something like this, but comes out to one byte longer, so nice work finding a shorter method
                      $endgroup$
                      – Jo King
                      Mar 29 at 0:39












                    • $begingroup$
                      @JoKing good catch. The things that happen when I golf too quickly after getting a working solution. I had a similar one but the damned lack of [-1] haha
                      $endgroup$
                      – guifa
                      Mar 29 at 0:49



















                    3












                    $begingroup$

                    C, 122 121 104 bytes





                    p(a,i){for(i=1;++i<a;)if(a%i<1)return 0;return a>1;}c(a,b){for(b=a;;b++)if(p(--a)|p(b))return p(b)?b:a;}


                    Use it calling function c() and passing as argument the number; it should return the closest prime.



                    Thanks to Embodiment of Ignorance for 1 byte saved a big improvement.



                    Try it online!






                    share|improve this answer











                    $endgroup$













                    • $begingroup$
                      But c() receives two parameters... Also, you can probably shorten the while(1) to for(;;) (untested, since I don't get how to run your code
                      $endgroup$
                      – Embodiment of Ignorance
                      Mar 28 at 5:03










                    • $begingroup$
                      @EmbodimentofIgnorance I wrote it and tested it all on an online c compiler, I could call c() passing only the first parameter. And you are right, for(;;) saves me a byte, only 117 left to get first place :)
                      $endgroup$
                      – Lince Assassino
                      Mar 28 at 11:30












                    • $begingroup$
                      110 bytes: #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/…
                      $endgroup$
                      – Embodiment of Ignorance
                      Mar 28 at 21:06










                    • $begingroup$
                      106: tio.run/…
                      $endgroup$
                      – Embodiment of Ignorance
                      Mar 28 at 21:12












                    • $begingroup$
                      101: tio.run/…
                      $endgroup$
                      – Embodiment of Ignorance
                      Mar 28 at 21:17





















                    3












                    $begingroup$


                    Wolfram Language (Mathematica), 52 bytes



                    If[PrimeQ[s=#],s,#&@@Nearest[s~NextPrime~{-1,1},s]]&


                    Try it online!






                    share|improve this answer











                    $endgroup$













                    • $begingroup$
                      You have an extra space that can be removed to save a byte.
                      $endgroup$
                      – Ben
                      Mar 29 at 16:03










                    • $begingroup$
                      @Ben you are right. thanx
                      $endgroup$
                      – J42161217
                      Mar 29 at 23:08



















                    2












                    $begingroup$

                    APL(NARS), 38 chars, 76 bytes



                    {⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}


                    0π is the test for prime, ¯1π the prev prime, 1π is the next prime; test:



                      f←{⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}
                    f¨80 100 5 9 532 1
                    79 101 5 7 523 2





                    share|improve this answer









                    $endgroup$





















                      2












                      $begingroup$


                      J, 19 15 bytes



                      (0{]/:|@-)p:@i.


                      Try it online!






                      share|improve this answer











                      $endgroup$





















                        2












                        $begingroup$


                        Perl 5, 59 bytes





                        $a=0;while((1x$_)=~/^.?$|^(..+?)1+$/){$_+=(-1)**$a*($a++)}


                        Try it online!



                        /^.?$|^(..+?)1+$/ is tricky regexp to check prime



                        (-1)**$a*($a++) generate sequence 0,-1, 2,-3 ...






                        share|improve this answer









                        $endgroup$





















                          2












                          $begingroup$


                          MathGolf, 10 bytes



                          ∞╒g¶áÅ-±├Þ


                          Try it online.



                          Explanation:





                          ∞            # Double the (implicit) input-integer
                          ╒ # Create a list in the range [1, 2*n]
                          g¶ # Filter so only the prime numbers remain
                          áÅ # Sort this list using the next two character:
                          -± # The absolute difference with the (implicit) input-integer
                          ├ # Push the first item of the list
                          # (unfortunately without popping the list itself, so:)
                          Þ # Discard everything from the stack except for the top
                          # (which is output implicitly as result)





                          share|improve this answer











                          $endgroup$













                          • $begingroup$
                            @JoKing Thanks! I knew Max thought about changing it, but didn't knew he actually did. The docs still state the old one.
                            $endgroup$
                            – Kevin Cruijssen
                            Mar 28 at 8:53










                          • $begingroup$
                            Ah, I use the mathgolf.txt file as reference, since it seems to be more up to date
                            $endgroup$
                            – Jo King
                            Mar 28 at 23:21










                          • $begingroup$
                            @JoKing Yeah, he told me yesterday about that file as well. Will use it from now on. :)
                            $endgroup$
                            – Kevin Cruijssen
                            Mar 29 at 7:23



















                          2












                          $begingroup$


                          Factor, 91 bytes



                          : p ( x -- x ) [ nprimes ] keep dupd [ - abs ] curry map swap zip natural-sort first last ;


                          Try it online!






                          share|improve this answer









                          $endgroup$





















                            2












                            $begingroup$


                            Python 2 (Cython), 96 bytes





                            l=lambda p:min(filter(lambda p:all(p%n for n in range(2,p)),range(2,p*3)),key=lambda x:abs(x-p))


                            Try it online!






                            share|improve this answer











                            $endgroup$













                            • $begingroup$
                              Might be able to save a couple bytes via r=range;...
                              $endgroup$
                              – Skyler
                              Mar 28 at 20:33






                            • 1




                              $begingroup$
                              @Arnauld, it now works for x=1
                              $endgroup$
                              – Snaddyvitch Dispenser
                              Mar 29 at 8:20



















                            2












                            $begingroup$


                            C# (Visual C# Interactive Compiler), 104 100 bytes



                            n=>{int r=0,t=0,m=n;while(r!=2){n+=(n<m)?t:-t;t++;r=0;for(int i=1;i<=n;i++)if(n%i==0)r++;}return n;}


                            Try it online!



                            Explanation:



                            int f(int n)
                            {
                            int r = 0; //stores the amount of factors of "n"
                            int t = 0; //increment used to cover all the integers surrounding "n"
                            int m = n; //placeholder to toggle between adding or substracting "t" to "n"

                            while (r != 2) //while the amount of factors found for "n" is different to 2 ("1" + itself)
                            {
                            n += (n < m) ? t : -t; //increment/decrement "n" by "t" (-0, -1, +2, -3, +4, -5,...)
                            t++;
                            r = 0;
                            for (int i = 1; i <= n; i++) //foreach number between "1" and "n" increment "r" if the remainder of its division with "n" is 0 (thus being a factor)
                            if (n % i == 0) r++;
                            }
                            return n;
                            }

                            Console.WriteLine(f(80)); //79





                            share|improve this answer











                            $endgroup$





















                              2












                              $begingroup$

                              Java 8, 88 87 bytes





                              n->{for(int c=0,s=0,d,N=n;c!=2;s++)for(c=d=1,n+=n<N?s:-s;d<n;)if(n%++d<1)c++;return n;}


                              Port of @NaturalNumberGuy's (first) C answer, so make sure to upvote him!!

                              -1 byte thanks to @OlivierGrégoire.



                              Try it online.



                              Explanation:



                              n->{               // Method with integer as both parameter and return-type
                              for(int c=0, // Counter-integer, starting at 0
                              s=0, // Step-integer, starting at 0 as well
                              d, // Divisor-integer, uninitialized
                              N=n; // Copy of the input-integer
                              c!=2; // Loop as long as the counter is not exactly 2 yet:
                              s++) // After every iteration: increase the step-integer by 1
                              for(c=d=1, // (Re)set both the counter and divisor to 1
                              n+=n<N? // If the input is smaller than the input-copy:
                              s // Increase the input by the step-integer
                              : // Else:
                              -s; // Decrease the input by the step-integer
                              d<n;) // Inner loop as long as the divisor is smaller than the input
                              if(n%++d // Increase the divisor by 1 first with `++d`
                              <1) // And if the input is evenly divisible by the divisor:
                              c++; // Increase the counter-integer by 1
                              return n;} // Return the now modified input-integer as result





                              share|improve this answer











                              $endgroup$





















                                2












                                $begingroup$


                                Java (JDK), 103 bytes





                                n->{int p=0,x=0,z=n,d;for(;p<1;p=p>0?z:0,z=z==n+x?n-++x:z+1)for(p=z/2,d=1;++d<z;)p=z%d<1?0:p;return p;}


                                Try it online!






                                share|improve this answer











                                $endgroup$













                                • $begingroup$
                                  Umm.. I had already create a port of his answer.. ;) Although yours is 1 byte shorter, so something is different. EDIT: Ah, I have a result-integer outside the loop, and you modify the input inside the loop, hence the -1 byte for ;. :) Do you want me to delete my answer?.. Feel free to copy the explanation.
                                  $endgroup$
                                  – Kevin Cruijssen
                                  Mar 29 at 12:50












                                • $begingroup$
                                  @KevinCruijssen Oops, rollbacked!
                                  $endgroup$
                                  – Olivier Grégoire
                                  Mar 29 at 12:59










                                • $begingroup$
                                  Sorry about that (and thanks for the -1 byte). I like your version as well, though. Already upvoted before I saw NaturalNumberGuy's answer.
                                  $endgroup$
                                  – Kevin Cruijssen
                                  Mar 29 at 12:59



















                                2












                                $begingroup$


                                Haskell, 79 74 bytes (thanks to Laikoni)



                                72 bytes as annonymus function (the initial "f=" could be removed in this case).





                                f=(!)(-1);n!x|x>1,all((>0).mod x)[2..x-1]=x|y<-x+n=last(-n+1:[-n-1|n>0])!y


                                Try it online!





                                original code:





                                f=(!)(-1);n!x|x>1&&all((>0).mod x)[2..x-1]=x|1>0=(last$(-n+1):[-n-1|n>0])!(x+n)


                                Try it online!



                                Explanation:





                                f x = (-1)!x

                                isPrime x = x > 1 && all (k -> x `mod` k /= 0)[2..x-1]
                                n!x | isPrime x = x -- return the first prime found
                                | n>0 = (-n-1)!(x+n) -- x is no prime, continue with x+n where n takes the
                                | otherwise = (-n+1)!(x+n) -- values -1,2,-3,4 .. in subsequent calls of (!)





                                share|improve this answer











                                $endgroup$









                                • 1




                                  $begingroup$
                                  Inside a guard you can use , instead of &&. (last$ ...) can be last(...), and the second guard 1>0 can be used for a binding to save parenthesis, e.g. y<-x+n.
                                  $endgroup$
                                  – Laikoni
                                  Mar 30 at 10:57










                                • $begingroup$
                                  Anonymous functions are generally allowed, so the initial f= does not need to be counted. Also the parenthesis enclosing (-1+n) can be dropped.
                                  $endgroup$
                                  – Laikoni
                                  Mar 30 at 11:22










                                • $begingroup$
                                  Thanks for the suggestions. I didn't know "," and bindings are allowed in function guards! But i don't really like the idea of an annonymous function as an answer. It doesn't feel right in my opinion.
                                  $endgroup$
                                  – Sachera
                                  Mar 31 at 2:58












                                • $begingroup$
                                  You can find more tips in our collection of tips for golfing in Haskell. There is also a Guide to Golfing Rules in Haskell and dedicated chat room: Of Monads and Men.
                                  $endgroup$
                                  – Laikoni
                                  Mar 31 at 22:13



















                                2












                                $begingroup$


                                VDM-SL, 161 bytes





                                f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})


                                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:



                                functions
                                f:nat1+>nat1
                                f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})


                                Explanation:



                                f(i)==                                        /* f is a function which takes a nat1 (natural number not including 0)*/
                                (lambda p:set of nat1 /* define a lambda which takes a set of nat1*/
                                &let z in set p be st /* which has an element z in the set such that */
                                forall m in set p /* for every element in the set*/
                                &abs(m-i) /* the difference between the element m and the input*/
                                >=abs(z-i) /* is greater than or equal to the difference between the element z and the input */
                                in z) /* and return z from the lambda */
                                ( /* apply this lambda to... */
                                { /* a set defined by comprehension as.. */
                                x| /* all elements x such that.. */
                                x in set{1,...,9**7} /* x is between 1 and 9^7 */
                                &forall y in set{2,...,1003} /* and for all values between 2 and 1003*/
                                &y<>x=>x mod y<>0 /* y is not x implies x is not divisible by y*/
                                }
                                )





                                share|improve this answer











                                $endgroup$





















                                  1












                                  $begingroup$


                                  C# (Visual C# Interactive Compiler), 112 bytes





                                  g=>Enumerable.Range(2,2<<20).Where(x=>Enumerable.Range(1,x).Count(y=>x%y<1)<3).OrderBy(x=>Math.Abs(x-g)).First()


                                  Try it online!



                                  Left shifts by 20 in submission but 10 in TIO so that TIO terminates for test cases.






                                  share|improve this answer









                                  $endgroup$





















                                    1












                                    $begingroup$

                                    Swift, 186 bytes



                                    func p(a:Int){let b=q(a:a,b:-1),c=q(a:a,b:1);print(a-b<=c-a ? b:c)}
                                    func q(a:Int,b:Int)->Int{var k=max(a,2),c=2;while k>c && c != a/2{if k%c==0{k+=b;c=2}else{c=c==2 ? c+1:c+2}};return k}


                                    Try it online!






                                    share|improve this answer









                                    $endgroup$

















                                      1 2
                                      next




                                      Your Answer





                                      StackExchange.ifUsing("editor", function () {
                                      return StackExchange.using("mathjaxEditing", function () {
                                      StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
                                      StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
                                      });
                                      });
                                      }, "mathjax-editing");

                                      StackExchange.ifUsing("editor", function () {
                                      StackExchange.using("externalEditor", function () {
                                      StackExchange.using("snippets", function () {
                                      StackExchange.snippets.init();
                                      });
                                      });
                                      }, "code-snippets");

                                      StackExchange.ready(function() {
                                      var channelOptions = {
                                      tags: "".split(" "),
                                      id: "200"
                                      };
                                      initTagRenderer("".split(" "), "".split(" "), channelOptions);

                                      StackExchange.using("externalEditor", function() {
                                      // Have to fire editor after snippets, if snippets enabled
                                      if (StackExchange.settings.snippets.snippetsEnabled) {
                                      StackExchange.using("snippets", function() {
                                      createEditor();
                                      });
                                      }
                                      else {
                                      createEditor();
                                      }
                                      });

                                      function createEditor() {
                                      StackExchange.prepareEditor({
                                      heartbeatType: 'answer',
                                      autoActivateHeartbeat: false,
                                      convertImagesToLinks: false,
                                      noModals: true,
                                      showLowRepImageUploadWarning: true,
                                      reputationToPostImages: null,
                                      bindNavPrevention: true,
                                      postfix: "",
                                      imageUploader: {
                                      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                                      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                                      allowUrls: true
                                      },
                                      onDemand: true,
                                      discardSelector: ".discard-answer"
                                      ,immediatelyShowMarkdownHelp:true
                                      });


                                      }
                                      });














                                      draft saved

                                      draft discarded


















                                      StackExchange.ready(
                                      function () {
                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f182305%2freturn-the-closest-prime-number%23new-answer', 'question_page');
                                      }
                                      );

                                      Post as a guest















                                      Required, but never shown

























                                      37 Answers
                                      37






                                      active

                                      oldest

                                      votes








                                      37 Answers
                                      37






                                      active

                                      oldest

                                      votes









                                      active

                                      oldest

                                      votes






                                      active

                                      oldest

                                      votes








                                      1 2
                                      next










                                      12












                                      $begingroup$

                                      JavaScript (ES6), 53 bytes





                                      n=>(g=(o,d=N=n+o)=>N%--d?g(o,d):d-1?g(o<0?-o:~o):N)``


                                      Try it online!



                                      Commented



                                      n => (            // n = input
                                      g = ( // g = recursive function taking:
                                      o, // o = offset
                                      d = // d = current divisor, initialized to N
                                      N = n + o // N = input + offset
                                      ) => //
                                      N % --d ? // decrement d; if d is not a divisor of N:
                                      g(o, d) // do recursive calls until it is
                                      : // else:
                                      d - 1 ? // if d is not equal to 1 (either N is composite or N = 1):
                                      g( // do a recursive call with the next offset:
                                      o < 0 ? // if o is negative:
                                      -o // make it positive (e.g. -1 -> +1)
                                      : // else:
                                      ~o // use -(o + 1) (e.g. +1 -> -2)
                                      ) // end of recursive call
                                      : // else (N is prime):
                                      N // stop recursion and return N
                                      )`` // initial call to g with o = [''] (zero-ish)





                                      share|improve this answer











                                      $endgroup$


















                                        12












                                        $begingroup$

                                        JavaScript (ES6), 53 bytes





                                        n=>(g=(o,d=N=n+o)=>N%--d?g(o,d):d-1?g(o<0?-o:~o):N)``


                                        Try it online!



                                        Commented



                                        n => (            // n = input
                                        g = ( // g = recursive function taking:
                                        o, // o = offset
                                        d = // d = current divisor, initialized to N
                                        N = n + o // N = input + offset
                                        ) => //
                                        N % --d ? // decrement d; if d is not a divisor of N:
                                        g(o, d) // do recursive calls until it is
                                        : // else:
                                        d - 1 ? // if d is not equal to 1 (either N is composite or N = 1):
                                        g( // do a recursive call with the next offset:
                                        o < 0 ? // if o is negative:
                                        -o // make it positive (e.g. -1 -> +1)
                                        : // else:
                                        ~o // use -(o + 1) (e.g. +1 -> -2)
                                        ) // end of recursive call
                                        : // else (N is prime):
                                        N // stop recursion and return N
                                        )`` // initial call to g with o = [''] (zero-ish)





                                        share|improve this answer











                                        $endgroup$
















                                          12












                                          12








                                          12





                                          $begingroup$

                                          JavaScript (ES6), 53 bytes





                                          n=>(g=(o,d=N=n+o)=>N%--d?g(o,d):d-1?g(o<0?-o:~o):N)``


                                          Try it online!



                                          Commented



                                          n => (            // n = input
                                          g = ( // g = recursive function taking:
                                          o, // o = offset
                                          d = // d = current divisor, initialized to N
                                          N = n + o // N = input + offset
                                          ) => //
                                          N % --d ? // decrement d; if d is not a divisor of N:
                                          g(o, d) // do recursive calls until it is
                                          : // else:
                                          d - 1 ? // if d is not equal to 1 (either N is composite or N = 1):
                                          g( // do a recursive call with the next offset:
                                          o < 0 ? // if o is negative:
                                          -o // make it positive (e.g. -1 -> +1)
                                          : // else:
                                          ~o // use -(o + 1) (e.g. +1 -> -2)
                                          ) // end of recursive call
                                          : // else (N is prime):
                                          N // stop recursion and return N
                                          )`` // initial call to g with o = [''] (zero-ish)





                                          share|improve this answer











                                          $endgroup$



                                          JavaScript (ES6), 53 bytes





                                          n=>(g=(o,d=N=n+o)=>N%--d?g(o,d):d-1?g(o<0?-o:~o):N)``


                                          Try it online!



                                          Commented



                                          n => (            // n = input
                                          g = ( // g = recursive function taking:
                                          o, // o = offset
                                          d = // d = current divisor, initialized to N
                                          N = n + o // N = input + offset
                                          ) => //
                                          N % --d ? // decrement d; if d is not a divisor of N:
                                          g(o, d) // do recursive calls until it is
                                          : // else:
                                          d - 1 ? // if d is not equal to 1 (either N is composite or N = 1):
                                          g( // do a recursive call with the next offset:
                                          o < 0 ? // if o is negative:
                                          -o // make it positive (e.g. -1 -> +1)
                                          : // else:
                                          ~o // use -(o + 1) (e.g. +1 -> -2)
                                          ) // end of recursive call
                                          : // else (N is prime):
                                          N // stop recursion and return N
                                          )`` // initial call to g with o = [''] (zero-ish)






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Mar 27 at 16:45

























                                          answered Mar 27 at 16:01









                                          ArnauldArnauld

                                          80.6k797334




                                          80.6k797334























                                              10












                                              $begingroup$


                                              05AB1E, 5 bytes



                                              Åps.x


                                              Try it online!
                                              or as a Test Suite



                                              Inefficient for big numbers






                                              share|improve this answer









                                              $endgroup$









                                              • 2




                                                $begingroup$
                                                Too bad Ån is "In case of a tie, the higher prime is pushed" Didn't even knew we had this builtin, tbh.
                                                $endgroup$
                                                – Kevin Cruijssen
                                                Mar 28 at 7:51










                                              • $begingroup$
                                                @KevinCruijssen: Neither did I until now :)
                                                $endgroup$
                                                – Emigna
                                                Mar 28 at 9:15
















                                              10












                                              $begingroup$


                                              05AB1E, 5 bytes



                                              Åps.x


                                              Try it online!
                                              or as a Test Suite



                                              Inefficient for big numbers






                                              share|improve this answer









                                              $endgroup$









                                              • 2




                                                $begingroup$
                                                Too bad Ån is "In case of a tie, the higher prime is pushed" Didn't even knew we had this builtin, tbh.
                                                $endgroup$
                                                – Kevin Cruijssen
                                                Mar 28 at 7:51










                                              • $begingroup$
                                                @KevinCruijssen: Neither did I until now :)
                                                $endgroup$
                                                – Emigna
                                                Mar 28 at 9:15














                                              10












                                              10








                                              10





                                              $begingroup$


                                              05AB1E, 5 bytes



                                              Åps.x


                                              Try it online!
                                              or as a Test Suite



                                              Inefficient for big numbers






                                              share|improve this answer









                                              $endgroup$




                                              05AB1E, 5 bytes



                                              Åps.x


                                              Try it online!
                                              or as a Test Suite



                                              Inefficient for big numbers







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Mar 27 at 15:17









                                              EmignaEmigna

                                              47.6k433145




                                              47.6k433145








                                              • 2




                                                $begingroup$
                                                Too bad Ån is "In case of a tie, the higher prime is pushed" Didn't even knew we had this builtin, tbh.
                                                $endgroup$
                                                – Kevin Cruijssen
                                                Mar 28 at 7:51










                                              • $begingroup$
                                                @KevinCruijssen: Neither did I until now :)
                                                $endgroup$
                                                – Emigna
                                                Mar 28 at 9:15














                                              • 2




                                                $begingroup$
                                                Too bad Ån is "In case of a tie, the higher prime is pushed" Didn't even knew we had this builtin, tbh.
                                                $endgroup$
                                                – Kevin Cruijssen
                                                Mar 28 at 7:51










                                              • $begingroup$
                                                @KevinCruijssen: Neither did I until now :)
                                                $endgroup$
                                                – Emigna
                                                Mar 28 at 9:15








                                              2




                                              2




                                              $begingroup$
                                              Too bad Ån is "In case of a tie, the higher prime is pushed" Didn't even knew we had this builtin, tbh.
                                              $endgroup$
                                              – Kevin Cruijssen
                                              Mar 28 at 7:51




                                              $begingroup$
                                              Too bad Ån is "In case of a tie, the higher prime is pushed" Didn't even knew we had this builtin, tbh.
                                              $endgroup$
                                              – Kevin Cruijssen
                                              Mar 28 at 7:51












                                              $begingroup$
                                              @KevinCruijssen: Neither did I until now :)
                                              $endgroup$
                                              – Emigna
                                              Mar 28 at 9:15




                                              $begingroup$
                                              @KevinCruijssen: Neither did I until now :)
                                              $endgroup$
                                              – Emigna
                                              Mar 28 at 9:15











                                              7












                                              $begingroup$


                                              Gaia, 3 bytes



                                              ṅD⌡


                                              Try it online!



                                              Rather slow for large inputs, but works given enough memory/time.



                                              I'm not sure why D⌡ implicitly pushes z again, but it makes this a remarkably short answer!



                                              ṅ	| implicit input z: push first z prime numbers, call it P
                                              D⌡ | take the absolute difference between P and (implicit) z,
                                              | returning the smallest value in P with the minimum absolute difference





                                              share|improve this answer











                                              $endgroup$


















                                                7












                                                $begingroup$


                                                Gaia, 3 bytes



                                                ṅD⌡


                                                Try it online!



                                                Rather slow for large inputs, but works given enough memory/time.



                                                I'm not sure why D⌡ implicitly pushes z again, but it makes this a remarkably short answer!



                                                ṅ	| implicit input z: push first z prime numbers, call it P
                                                D⌡ | take the absolute difference between P and (implicit) z,
                                                | returning the smallest value in P with the minimum absolute difference





                                                share|improve this answer











                                                $endgroup$
















                                                  7












                                                  7








                                                  7





                                                  $begingroup$


                                                  Gaia, 3 bytes



                                                  ṅD⌡


                                                  Try it online!



                                                  Rather slow for large inputs, but works given enough memory/time.



                                                  I'm not sure why D⌡ implicitly pushes z again, but it makes this a remarkably short answer!



                                                  ṅ	| implicit input z: push first z prime numbers, call it P
                                                  D⌡ | take the absolute difference between P and (implicit) z,
                                                  | returning the smallest value in P with the minimum absolute difference





                                                  share|improve this answer











                                                  $endgroup$




                                                  Gaia, 3 bytes



                                                  ṅD⌡


                                                  Try it online!



                                                  Rather slow for large inputs, but works given enough memory/time.



                                                  I'm not sure why D⌡ implicitly pushes z again, but it makes this a remarkably short answer!



                                                  ṅ	| implicit input z: push first z prime numbers, call it P
                                                  D⌡ | take the absolute difference between P and (implicit) z,
                                                  | returning the smallest value in P with the minimum absolute difference






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Mar 27 at 20:30

























                                                  answered Mar 27 at 20:23









                                                  GiuseppeGiuseppe

                                                  17.6k31153




                                                  17.6k31153























                                                      7












                                                      $begingroup$


                                                      Octave, 40 bytes





                                                      @(n)p([~,k]=min(abs(n-(p=primes(2*n)))))


                                                      Try it online!



                                                      This uses the fact that there is always a prime between n and 2*n (Bertrand–Chebyshev theorem).



                                                      How it works



                                                      @(n)p([~,k]=min(abs(n-(p=primes(2*n)))))

                                                      @(n) % Define anonymous function with input n
                                                      p=primes(2*n) % Vector of primes up to 2*n. Assign to p
                                                      abs(n-( )) % Absolute difference between n and each prime
                                                      [~,k]=min( ) % Index of first minimum (assign to k; not used)
                                                      p( ) % Apply that index to p





                                                      share|improve this answer











                                                      $endgroup$


















                                                        7












                                                        $begingroup$


                                                        Octave, 40 bytes





                                                        @(n)p([~,k]=min(abs(n-(p=primes(2*n)))))


                                                        Try it online!



                                                        This uses the fact that there is always a prime between n and 2*n (Bertrand–Chebyshev theorem).



                                                        How it works



                                                        @(n)p([~,k]=min(abs(n-(p=primes(2*n)))))

                                                        @(n) % Define anonymous function with input n
                                                        p=primes(2*n) % Vector of primes up to 2*n. Assign to p
                                                        abs(n-( )) % Absolute difference between n and each prime
                                                        [~,k]=min( ) % Index of first minimum (assign to k; not used)
                                                        p( ) % Apply that index to p





                                                        share|improve this answer











                                                        $endgroup$
















                                                          7












                                                          7








                                                          7





                                                          $begingroup$


                                                          Octave, 40 bytes





                                                          @(n)p([~,k]=min(abs(n-(p=primes(2*n)))))


                                                          Try it online!



                                                          This uses the fact that there is always a prime between n and 2*n (Bertrand–Chebyshev theorem).



                                                          How it works



                                                          @(n)p([~,k]=min(abs(n-(p=primes(2*n)))))

                                                          @(n) % Define anonymous function with input n
                                                          p=primes(2*n) % Vector of primes up to 2*n. Assign to p
                                                          abs(n-( )) % Absolute difference between n and each prime
                                                          [~,k]=min( ) % Index of first minimum (assign to k; not used)
                                                          p( ) % Apply that index to p





                                                          share|improve this answer











                                                          $endgroup$




                                                          Octave, 40 bytes





                                                          @(n)p([~,k]=min(abs(n-(p=primes(2*n)))))


                                                          Try it online!



                                                          This uses the fact that there is always a prime between n and 2*n (Bertrand–Chebyshev theorem).



                                                          How it works



                                                          @(n)p([~,k]=min(abs(n-(p=primes(2*n)))))

                                                          @(n) % Define anonymous function with input n
                                                          p=primes(2*n) % Vector of primes up to 2*n. Assign to p
                                                          abs(n-( )) % Absolute difference between n and each prime
                                                          [~,k]=min( ) % Index of first minimum (assign to k; not used)
                                                          p( ) % Apply that index to p






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Mar 27 at 23:03

























                                                          answered Mar 27 at 18:33









                                                          Luis MendoLuis Mendo

                                                          75.3k889292




                                                          75.3k889292























                                                              6












                                                              $begingroup$


                                                              Japt, 5 bytes



                                                              _j}cU


                                                              Try it or run all test cases



                                                              _j}cU     :Implicit input of integer U
                                                              _ :Function taking an integer as an argument
                                                              j : Test if integer is prime
                                                              } :End function
                                                              cU :Return the first integer in [U,U-1,U+1,U-2,...] that returns true





                                                              share|improve this answer











                                                              $endgroup$


















                                                                6












                                                                $begingroup$


                                                                Japt, 5 bytes



                                                                _j}cU


                                                                Try it or run all test cases



                                                                _j}cU     :Implicit input of integer U
                                                                _ :Function taking an integer as an argument
                                                                j : Test if integer is prime
                                                                } :End function
                                                                cU :Return the first integer in [U,U-1,U+1,U-2,...] that returns true





                                                                share|improve this answer











                                                                $endgroup$
















                                                                  6












                                                                  6








                                                                  6





                                                                  $begingroup$


                                                                  Japt, 5 bytes



                                                                  _j}cU


                                                                  Try it or run all test cases



                                                                  _j}cU     :Implicit input of integer U
                                                                  _ :Function taking an integer as an argument
                                                                  j : Test if integer is prime
                                                                  } :End function
                                                                  cU :Return the first integer in [U,U-1,U+1,U-2,...] that returns true





                                                                  share|improve this answer











                                                                  $endgroup$




                                                                  Japt, 5 bytes



                                                                  _j}cU


                                                                  Try it or run all test cases



                                                                  _j}cU     :Implicit input of integer U
                                                                  _ :Function taking an integer as an argument
                                                                  j : Test if integer is prime
                                                                  } :End function
                                                                  cU :Return the first integer in [U,U-1,U+1,U-2,...] that returns true






                                                                  share|improve this answer














                                                                  share|improve this answer



                                                                  share|improve this answer








                                                                  edited Mar 28 at 17:38

























                                                                  answered Mar 27 at 15:43









                                                                  ShaggyShaggy

                                                                  18.9k21768




                                                                  18.9k21768























                                                                      5












                                                                      $begingroup$


                                                                      05AB1E, 4 bytes



                                                                      z-Ån


                                                                      Try it online!






                                                                      share|improve this answer









                                                                      $endgroup$


















                                                                        5












                                                                        $begingroup$


                                                                        05AB1E, 4 bytes



                                                                        z-Ån


                                                                        Try it online!






                                                                        share|improve this answer









                                                                        $endgroup$
















                                                                          5












                                                                          5








                                                                          5





                                                                          $begingroup$


                                                                          05AB1E, 4 bytes



                                                                          z-Ån


                                                                          Try it online!






                                                                          share|improve this answer









                                                                          $endgroup$




                                                                          05AB1E, 4 bytes



                                                                          z-Ån


                                                                          Try it online!







                                                                          share|improve this answer












                                                                          share|improve this answer



                                                                          share|improve this answer










                                                                          answered Mar 28 at 12:48









                                                                          GrimyGrimy

                                                                          2,6411019




                                                                          2,6411019























                                                                              4












                                                                              $begingroup$

                                                                              Pyth, 10 bytes



                                                                              haDQfP_TSy


                                                                              Try it online here, or verify all the test cases at once here.



                                                                              haDQfP_TSyQ   Implicit: Q=eval(input())
                                                                              Trailing Q inferred
                                                                              yQ 2 * Q
                                                                              S Range from 1 to the above
                                                                              f Filter keep the elements of the above, as T, where:
                                                                              P_T Is T prime?
                                                                              D Order the above by...
                                                                              a Q ... absolute difference between each element and Q
                                                                              This is a stable sort, so smaller primes will be sorted before larger ones if difference is the same
                                                                              h Take the first element of the above, implicit print





                                                                              share|improve this answer









                                                                              $endgroup$


















                                                                                4












                                                                                $begingroup$

                                                                                Pyth, 10 bytes



                                                                                haDQfP_TSy


                                                                                Try it online here, or verify all the test cases at once here.



                                                                                haDQfP_TSyQ   Implicit: Q=eval(input())
                                                                                Trailing Q inferred
                                                                                yQ 2 * Q
                                                                                S Range from 1 to the above
                                                                                f Filter keep the elements of the above, as T, where:
                                                                                P_T Is T prime?
                                                                                D Order the above by...
                                                                                a Q ... absolute difference between each element and Q
                                                                                This is a stable sort, so smaller primes will be sorted before larger ones if difference is the same
                                                                                h Take the first element of the above, implicit print





                                                                                share|improve this answer









                                                                                $endgroup$
















                                                                                  4












                                                                                  4








                                                                                  4





                                                                                  $begingroup$

                                                                                  Pyth, 10 bytes



                                                                                  haDQfP_TSy


                                                                                  Try it online here, or verify all the test cases at once here.



                                                                                  haDQfP_TSyQ   Implicit: Q=eval(input())
                                                                                  Trailing Q inferred
                                                                                  yQ 2 * Q
                                                                                  S Range from 1 to the above
                                                                                  f Filter keep the elements of the above, as T, where:
                                                                                  P_T Is T prime?
                                                                                  D Order the above by...
                                                                                  a Q ... absolute difference between each element and Q
                                                                                  This is a stable sort, so smaller primes will be sorted before larger ones if difference is the same
                                                                                  h Take the first element of the above, implicit print





                                                                                  share|improve this answer









                                                                                  $endgroup$



                                                                                  Pyth, 10 bytes



                                                                                  haDQfP_TSy


                                                                                  Try it online here, or verify all the test cases at once here.



                                                                                  haDQfP_TSyQ   Implicit: Q=eval(input())
                                                                                  Trailing Q inferred
                                                                                  yQ 2 * Q
                                                                                  S Range from 1 to the above
                                                                                  f Filter keep the elements of the above, as T, where:
                                                                                  P_T Is T prime?
                                                                                  D Order the above by...
                                                                                  a Q ... absolute difference between each element and Q
                                                                                  This is a stable sort, so smaller primes will be sorted before larger ones if difference is the same
                                                                                  h Take the first element of the above, implicit print






                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered Mar 27 at 15:46









                                                                                  SokSok

                                                                                  4,187925




                                                                                  4,187925























                                                                                      4












                                                                                      $begingroup$


                                                                                      Jelly, 9 7 bytes



                                                                                      ḤÆRạÞµḢ


                                                                                      Try it online!



                                                                                      Slow for larger input, but works ok for the requested range. Thanks to @EriktheOutgolfer for saving 2 bytes!






                                                                                      share|improve this answer











                                                                                      $endgroup$













                                                                                      • $begingroup$
                                                                                        Hey, that's clever! Save two by substituting _A¥ with (absolute difference). Oh, and can really be .
                                                                                        $endgroup$
                                                                                        – Erik the Outgolfer
                                                                                        Mar 27 at 19:08












                                                                                      • $begingroup$
                                                                                        @EriktheOutgolfer thanks. Surely using won’t always work? It means that only primes up to n+1 will be found, while the closest might be n+2.
                                                                                        $endgroup$
                                                                                        – Nick Kennedy
                                                                                        Mar 27 at 22:39










                                                                                      • $begingroup$
                                                                                        Hm, that's a concern.
                                                                                        $endgroup$
                                                                                        – Erik the Outgolfer
                                                                                        Mar 27 at 22:40


















                                                                                      4












                                                                                      $begingroup$


                                                                                      Jelly, 9 7 bytes



                                                                                      ḤÆRạÞµḢ


                                                                                      Try it online!



                                                                                      Slow for larger input, but works ok for the requested range. Thanks to @EriktheOutgolfer for saving 2 bytes!






                                                                                      share|improve this answer











                                                                                      $endgroup$













                                                                                      • $begingroup$
                                                                                        Hey, that's clever! Save two by substituting _A¥ with (absolute difference). Oh, and can really be .
                                                                                        $endgroup$
                                                                                        – Erik the Outgolfer
                                                                                        Mar 27 at 19:08












                                                                                      • $begingroup$
                                                                                        @EriktheOutgolfer thanks. Surely using won’t always work? It means that only primes up to n+1 will be found, while the closest might be n+2.
                                                                                        $endgroup$
                                                                                        – Nick Kennedy
                                                                                        Mar 27 at 22:39










                                                                                      • $begingroup$
                                                                                        Hm, that's a concern.
                                                                                        $endgroup$
                                                                                        – Erik the Outgolfer
                                                                                        Mar 27 at 22:40
















                                                                                      4












                                                                                      4








                                                                                      4





                                                                                      $begingroup$


                                                                                      Jelly, 9 7 bytes



                                                                                      ḤÆRạÞµḢ


                                                                                      Try it online!



                                                                                      Slow for larger input, but works ok for the requested range. Thanks to @EriktheOutgolfer for saving 2 bytes!






                                                                                      share|improve this answer











                                                                                      $endgroup$




                                                                                      Jelly, 9 7 bytes



                                                                                      ḤÆRạÞµḢ


                                                                                      Try it online!



                                                                                      Slow for larger input, but works ok for the requested range. Thanks to @EriktheOutgolfer for saving 2 bytes!







                                                                                      share|improve this answer














                                                                                      share|improve this answer



                                                                                      share|improve this answer








                                                                                      edited Mar 27 at 19:10

























                                                                                      answered Mar 27 at 18:49









                                                                                      Nick KennedyNick Kennedy

                                                                                      1,36649




                                                                                      1,36649












                                                                                      • $begingroup$
                                                                                        Hey, that's clever! Save two by substituting _A¥ with (absolute difference). Oh, and can really be .
                                                                                        $endgroup$
                                                                                        – Erik the Outgolfer
                                                                                        Mar 27 at 19:08












                                                                                      • $begingroup$
                                                                                        @EriktheOutgolfer thanks. Surely using won’t always work? It means that only primes up to n+1 will be found, while the closest might be n+2.
                                                                                        $endgroup$
                                                                                        – Nick Kennedy
                                                                                        Mar 27 at 22:39










                                                                                      • $begingroup$
                                                                                        Hm, that's a concern.
                                                                                        $endgroup$
                                                                                        – Erik the Outgolfer
                                                                                        Mar 27 at 22:40




















                                                                                      • $begingroup$
                                                                                        Hey, that's clever! Save two by substituting _A¥ with (absolute difference). Oh, and can really be .
                                                                                        $endgroup$
                                                                                        – Erik the Outgolfer
                                                                                        Mar 27 at 19:08












                                                                                      • $begingroup$
                                                                                        @EriktheOutgolfer thanks. Surely using won’t always work? It means that only primes up to n+1 will be found, while the closest might be n+2.
                                                                                        $endgroup$
                                                                                        – Nick Kennedy
                                                                                        Mar 27 at 22:39










                                                                                      • $begingroup$
                                                                                        Hm, that's a concern.
                                                                                        $endgroup$
                                                                                        – Erik the Outgolfer
                                                                                        Mar 27 at 22:40


















                                                                                      $begingroup$
                                                                                      Hey, that's clever! Save two by substituting _A¥ with (absolute difference). Oh, and can really be .
                                                                                      $endgroup$
                                                                                      – Erik the Outgolfer
                                                                                      Mar 27 at 19:08






                                                                                      $begingroup$
                                                                                      Hey, that's clever! Save two by substituting _A¥ with (absolute difference). Oh, and can really be .
                                                                                      $endgroup$
                                                                                      – Erik the Outgolfer
                                                                                      Mar 27 at 19:08














                                                                                      $begingroup$
                                                                                      @EriktheOutgolfer thanks. Surely using won’t always work? It means that only primes up to n+1 will be found, while the closest might be n+2.
                                                                                      $endgroup$
                                                                                      – Nick Kennedy
                                                                                      Mar 27 at 22:39




                                                                                      $begingroup$
                                                                                      @EriktheOutgolfer thanks. Surely using won’t always work? It means that only primes up to n+1 will be found, while the closest might be n+2.
                                                                                      $endgroup$
                                                                                      – Nick Kennedy
                                                                                      Mar 27 at 22:39












                                                                                      $begingroup$
                                                                                      Hm, that's a concern.
                                                                                      $endgroup$
                                                                                      – Erik the Outgolfer
                                                                                      Mar 27 at 22:40






                                                                                      $begingroup$
                                                                                      Hm, that's a concern.
                                                                                      $endgroup$
                                                                                      – Erik the Outgolfer
                                                                                      Mar 27 at 22:40













                                                                                      4












                                                                                      $begingroup$


                                                                                      Wolfram Language (Mathematica), 31 bytes



                                                                                      Nearest[Prime~Array~78499,#,1]&


                                                                                      Try it online!



                                                                                                                    & (*pure function*)
                                                                                      Prime~Array~78499 (*among the (ascending) first 78499 primes*)
                                                                                      1 (*select one*)
                                                                                      Nearest[ ,#, ] (*which is nearest to the argument*)


                                                                                      1000003 is the 78499th prime. Nearest prioritizes values which appear earlier in the list (which are lower).






                                                                                      share|improve this answer











                                                                                      $endgroup$









                                                                                      • 4




                                                                                        $begingroup$
                                                                                        Nearest[Prime@Range@#,#,1]& for 27
                                                                                        $endgroup$
                                                                                        – Ben
                                                                                        Mar 29 at 16:10
















                                                                                      4












                                                                                      $begingroup$


                                                                                      Wolfram Language (Mathematica), 31 bytes



                                                                                      Nearest[Prime~Array~78499,#,1]&


                                                                                      Try it online!



                                                                                                                    & (*pure function*)
                                                                                      Prime~Array~78499 (*among the (ascending) first 78499 primes*)
                                                                                      1 (*select one*)
                                                                                      Nearest[ ,#, ] (*which is nearest to the argument*)


                                                                                      1000003 is the 78499th prime. Nearest prioritizes values which appear earlier in the list (which are lower).






                                                                                      share|improve this answer











                                                                                      $endgroup$









                                                                                      • 4




                                                                                        $begingroup$
                                                                                        Nearest[Prime@Range@#,#,1]& for 27
                                                                                        $endgroup$
                                                                                        – Ben
                                                                                        Mar 29 at 16:10














                                                                                      4












                                                                                      4








                                                                                      4





                                                                                      $begingroup$


                                                                                      Wolfram Language (Mathematica), 31 bytes



                                                                                      Nearest[Prime~Array~78499,#,1]&


                                                                                      Try it online!



                                                                                                                    & (*pure function*)
                                                                                      Prime~Array~78499 (*among the (ascending) first 78499 primes*)
                                                                                      1 (*select one*)
                                                                                      Nearest[ ,#, ] (*which is nearest to the argument*)


                                                                                      1000003 is the 78499th prime. Nearest prioritizes values which appear earlier in the list (which are lower).






                                                                                      share|improve this answer











                                                                                      $endgroup$




                                                                                      Wolfram Language (Mathematica), 31 bytes



                                                                                      Nearest[Prime~Array~78499,#,1]&


                                                                                      Try it online!



                                                                                                                    & (*pure function*)
                                                                                      Prime~Array~78499 (*among the (ascending) first 78499 primes*)
                                                                                      1 (*select one*)
                                                                                      Nearest[ ,#, ] (*which is nearest to the argument*)


                                                                                      1000003 is the 78499th prime. Nearest prioritizes values which appear earlier in the list (which are lower).







                                                                                      share|improve this answer














                                                                                      share|improve this answer



                                                                                      share|improve this answer








                                                                                      edited Mar 29 at 4:19

























                                                                                      answered Mar 28 at 23:46









                                                                                      attinatattinat

                                                                                      4797




                                                                                      4797








                                                                                      • 4




                                                                                        $begingroup$
                                                                                        Nearest[Prime@Range@#,#,1]& for 27
                                                                                        $endgroup$
                                                                                        – Ben
                                                                                        Mar 29 at 16:10














                                                                                      • 4




                                                                                        $begingroup$
                                                                                        Nearest[Prime@Range@#,#,1]& for 27
                                                                                        $endgroup$
                                                                                        – Ben
                                                                                        Mar 29 at 16:10








                                                                                      4




                                                                                      4




                                                                                      $begingroup$
                                                                                      Nearest[Prime@Range@#,#,1]& for 27
                                                                                      $endgroup$
                                                                                      – Ben
                                                                                      Mar 29 at 16:10




                                                                                      $begingroup$
                                                                                      Nearest[Prime@Range@#,#,1]& for 27
                                                                                      $endgroup$
                                                                                      – Ben
                                                                                      Mar 29 at 16:10











                                                                                      4












                                                                                      $begingroup$


                                                                                      Brachylog, 7 5 bytes



                                                                                      ;I≜-ṗ


                                                                                      Try it online!



                                                                                      Saved 2 bytes thanks to @DLosc.



                                                                                      Explanation



                                                                                      ;I≜      Label an unknown integer I (tries 0, then 1, then -1, then 2, etc.)
                                                                                      - Subtract I from the input
                                                                                      ṗ The result must be prime





                                                                                      share|improve this answer











                                                                                      $endgroup$













                                                                                      • $begingroup$
                                                                                        @DLosc Mostly because I am stupid. Thanks.
                                                                                        $endgroup$
                                                                                        – Fatalize
                                                                                        Mar 29 at 8:26










                                                                                      • $begingroup$
                                                                                        I think we just approached it from different directions. You were thinking about from the start, I assume, whereas I was thinking about pairing and subtracting and only later realized I'd need to make it work. :)
                                                                                        $endgroup$
                                                                                        – DLosc
                                                                                        Mar 29 at 21:27
















                                                                                      4












                                                                                      $begingroup$


                                                                                      Brachylog, 7 5 bytes



                                                                                      ;I≜-ṗ


                                                                                      Try it online!



                                                                                      Saved 2 bytes thanks to @DLosc.



                                                                                      Explanation



                                                                                      ;I≜      Label an unknown integer I (tries 0, then 1, then -1, then 2, etc.)
                                                                                      - Subtract I from the input
                                                                                      ṗ The result must be prime





                                                                                      share|improve this answer











                                                                                      $endgroup$













                                                                                      • $begingroup$
                                                                                        @DLosc Mostly because I am stupid. Thanks.
                                                                                        $endgroup$
                                                                                        – Fatalize
                                                                                        Mar 29 at 8:26










                                                                                      • $begingroup$
                                                                                        I think we just approached it from different directions. You were thinking about from the start, I assume, whereas I was thinking about pairing and subtracting and only later realized I'd need to make it work. :)
                                                                                        $endgroup$
                                                                                        – DLosc
                                                                                        Mar 29 at 21:27














                                                                                      4












                                                                                      4








                                                                                      4





                                                                                      $begingroup$


                                                                                      Brachylog, 7 5 bytes



                                                                                      ;I≜-ṗ


                                                                                      Try it online!



                                                                                      Saved 2 bytes thanks to @DLosc.



                                                                                      Explanation



                                                                                      ;I≜      Label an unknown integer I (tries 0, then 1, then -1, then 2, etc.)
                                                                                      - Subtract I from the input
                                                                                      ṗ The result must be prime





                                                                                      share|improve this answer











                                                                                      $endgroup$




                                                                                      Brachylog, 7 5 bytes



                                                                                      ;I≜-ṗ


                                                                                      Try it online!



                                                                                      Saved 2 bytes thanks to @DLosc.



                                                                                      Explanation



                                                                                      ;I≜      Label an unknown integer I (tries 0, then 1, then -1, then 2, etc.)
                                                                                      - Subtract I from the input
                                                                                      ṗ The result must be prime






                                                                                      share|improve this answer














                                                                                      share|improve this answer



                                                                                      share|improve this answer








                                                                                      edited Mar 29 at 8:26

























                                                                                      answered Mar 28 at 15:11









                                                                                      FatalizeFatalize

                                                                                      28k449136




                                                                                      28k449136












                                                                                      • $begingroup$
                                                                                        @DLosc Mostly because I am stupid. Thanks.
                                                                                        $endgroup$
                                                                                        – Fatalize
                                                                                        Mar 29 at 8:26










                                                                                      • $begingroup$
                                                                                        I think we just approached it from different directions. You were thinking about from the start, I assume, whereas I was thinking about pairing and subtracting and only later realized I'd need to make it work. :)
                                                                                        $endgroup$
                                                                                        – DLosc
                                                                                        Mar 29 at 21:27


















                                                                                      • $begingroup$
                                                                                        @DLosc Mostly because I am stupid. Thanks.
                                                                                        $endgroup$
                                                                                        – Fatalize
                                                                                        Mar 29 at 8:26










                                                                                      • $begingroup$
                                                                                        I think we just approached it from different directions. You were thinking about from the start, I assume, whereas I was thinking about pairing and subtracting and only later realized I'd need to make it work. :)
                                                                                        $endgroup$
                                                                                        – DLosc
                                                                                        Mar 29 at 21:27
















                                                                                      $begingroup$
                                                                                      @DLosc Mostly because I am stupid. Thanks.
                                                                                      $endgroup$
                                                                                      – Fatalize
                                                                                      Mar 29 at 8:26




                                                                                      $begingroup$
                                                                                      @DLosc Mostly because I am stupid. Thanks.
                                                                                      $endgroup$
                                                                                      – Fatalize
                                                                                      Mar 29 at 8:26












                                                                                      $begingroup$
                                                                                      I think we just approached it from different directions. You were thinking about from the start, I assume, whereas I was thinking about pairing and subtracting and only later realized I'd need to make it work. :)
                                                                                      $endgroup$
                                                                                      – DLosc
                                                                                      Mar 29 at 21:27




                                                                                      $begingroup$
                                                                                      I think we just approached it from different directions. You were thinking about from the start, I assume, whereas I was thinking about pairing and subtracting and only later realized I'd need to make it work. :)
                                                                                      $endgroup$
                                                                                      – DLosc
                                                                                      Mar 29 at 21:27











                                                                                      4












                                                                                      $begingroup$


                                                                                      C (gcc), 87 76 74 72 bytes



                                                                                      Optimization of innat3's C# (Visual C# Interactive Compiler), 100 bytes



                                                                                      f(n,i,t,r,m){for(t=0,m=n;r-2;t++)for(r=i=1,n+=n<m?t:-t;i<n;n%++i||r++);}


                                                                                      Try it online!






                                                                                      share|improve this answer











                                                                                      $endgroup$













                                                                                      • $begingroup$
                                                                                        Hello and welcome to PPCG. A few tips: r!=2 is equivalent to r-2, n%++i?0:r++ can most likely be n%++i||r++.
                                                                                        $endgroup$
                                                                                        – Jonathan Frech
                                                                                        Mar 29 at 13:11










                                                                                      • $begingroup$
                                                                                        I didn't immediately see that. Thanks.
                                                                                        $endgroup$
                                                                                        – Natural Number Guy
                                                                                        Mar 29 at 15:13
















                                                                                      4












                                                                                      $begingroup$


                                                                                      C (gcc), 87 76 74 72 bytes



                                                                                      Optimization of innat3's C# (Visual C# Interactive Compiler), 100 bytes



                                                                                      f(n,i,t,r,m){for(t=0,m=n;r-2;t++)for(r=i=1,n+=n<m?t:-t;i<n;n%++i||r++);}


                                                                                      Try it online!






                                                                                      share|improve this answer











                                                                                      $endgroup$













                                                                                      • $begingroup$
                                                                                        Hello and welcome to PPCG. A few tips: r!=2 is equivalent to r-2, n%++i?0:r++ can most likely be n%++i||r++.
                                                                                        $endgroup$
                                                                                        – Jonathan Frech
                                                                                        Mar 29 at 13:11










                                                                                      • $begingroup$
                                                                                        I didn't immediately see that. Thanks.
                                                                                        $endgroup$
                                                                                        – Natural Number Guy
                                                                                        Mar 29 at 15:13














                                                                                      4












                                                                                      4








                                                                                      4





                                                                                      $begingroup$


                                                                                      C (gcc), 87 76 74 72 bytes



                                                                                      Optimization of innat3's C# (Visual C# Interactive Compiler), 100 bytes



                                                                                      f(n,i,t,r,m){for(t=0,m=n;r-2;t++)for(r=i=1,n+=n<m?t:-t;i<n;n%++i||r++);}


                                                                                      Try it online!






                                                                                      share|improve this answer











                                                                                      $endgroup$




                                                                                      C (gcc), 87 76 74 72 bytes



                                                                                      Optimization of innat3's C# (Visual C# Interactive Compiler), 100 bytes



                                                                                      f(n,i,t,r,m){for(t=0,m=n;r-2;t++)for(r=i=1,n+=n<m?t:-t;i<n;n%++i||r++);}


                                                                                      Try it online!







                                                                                      share|improve this answer














                                                                                      share|improve this answer



                                                                                      share|improve this answer








                                                                                      edited Mar 29 at 15:24

























                                                                                      answered Mar 29 at 11:55









                                                                                      Natural Number GuyNatural Number Guy

                                                                                      1516




                                                                                      1516












                                                                                      • $begingroup$
                                                                                        Hello and welcome to PPCG. A few tips: r!=2 is equivalent to r-2, n%++i?0:r++ can most likely be n%++i||r++.
                                                                                        $endgroup$
                                                                                        – Jonathan Frech
                                                                                        Mar 29 at 13:11










                                                                                      • $begingroup$
                                                                                        I didn't immediately see that. Thanks.
                                                                                        $endgroup$
                                                                                        – Natural Number Guy
                                                                                        Mar 29 at 15:13


















                                                                                      • $begingroup$
                                                                                        Hello and welcome to PPCG. A few tips: r!=2 is equivalent to r-2, n%++i?0:r++ can most likely be n%++i||r++.
                                                                                        $endgroup$
                                                                                        – Jonathan Frech
                                                                                        Mar 29 at 13:11










                                                                                      • $begingroup$
                                                                                        I didn't immediately see that. Thanks.
                                                                                        $endgroup$
                                                                                        – Natural Number Guy
                                                                                        Mar 29 at 15:13
















                                                                                      $begingroup$
                                                                                      Hello and welcome to PPCG. A few tips: r!=2 is equivalent to r-2, n%++i?0:r++ can most likely be n%++i||r++.
                                                                                      $endgroup$
                                                                                      – Jonathan Frech
                                                                                      Mar 29 at 13:11




                                                                                      $begingroup$
                                                                                      Hello and welcome to PPCG. A few tips: r!=2 is equivalent to r-2, n%++i?0:r++ can most likely be n%++i||r++.
                                                                                      $endgroup$
                                                                                      – Jonathan Frech
                                                                                      Mar 29 at 13:11












                                                                                      $begingroup$
                                                                                      I didn't immediately see that. Thanks.
                                                                                      $endgroup$
                                                                                      – Natural Number Guy
                                                                                      Mar 29 at 15:13




                                                                                      $begingroup$
                                                                                      I didn't immediately see that. Thanks.
                                                                                      $endgroup$
                                                                                      – Natural Number Guy
                                                                                      Mar 29 at 15:13











                                                                                      3












                                                                                      $begingroup$


                                                                                      Tidy, 43 bytes



                                                                                      {x:(prime↦splice(]x,-1,-∞],[x,∞]))@0}


                                                                                      Try it online!



                                                                                      Explanation



                                                                                      This is a lambda with parameter x. This works by creating the following sequence:



                                                                                      [x - 1, x, x - 2, x + 1, x - 3, x + 2, x - 4, x + 3, ...]


                                                                                      This is splicing together the two sequences ]x, -1, -∞] (left-closed, right-open) and [x, ∞] (both open).



                                                                                      For x = 80, this looks like:



                                                                                      [79, 80, 78, 81, 77, 82, 76, 83, 75, 84, 74, 85, ...]


                                                                                      Then, we use f↦s to select all elements from s satisfying f. In this case, we filter out all composite numbers, leaving only the prime ones. For the same x, this becomes:



                                                                                      [79, 83, 73, 71, 89, 67, 97, 61, 59, 101, 103, 53, ...]


                                                                                      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 with x - 1 is spliced in first.



                                                                                      Note: Only one of x and x - 1 can be prime, so it is okay that the spliced sequence starts with x - 1. Though the sequence could be open on both sides ([x,-1,-∞]), this would needlessly include x twice in the sequence. So, for sake of "efficiency", I chose the left-closed version (also because I like to show off Tidy).






                                                                                      share|improve this answer









                                                                                      $endgroup$


















                                                                                        3












                                                                                        $begingroup$


                                                                                        Tidy, 43 bytes



                                                                                        {x:(prime↦splice(]x,-1,-∞],[x,∞]))@0}


                                                                                        Try it online!



                                                                                        Explanation



                                                                                        This is a lambda with parameter x. This works by creating the following sequence:



                                                                                        [x - 1, x, x - 2, x + 1, x - 3, x + 2, x - 4, x + 3, ...]


                                                                                        This is splicing together the two sequences ]x, -1, -∞] (left-closed, right-open) and [x, ∞] (both open).



                                                                                        For x = 80, this looks like:



                                                                                        [79, 80, 78, 81, 77, 82, 76, 83, 75, 84, 74, 85, ...]


                                                                                        Then, we use f↦s to select all elements from s satisfying f. In this case, we filter out all composite numbers, leaving only the prime ones. For the same x, this becomes:



                                                                                        [79, 83, 73, 71, 89, 67, 97, 61, 59, 101, 103, 53, ...]


                                                                                        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 with x - 1 is spliced in first.



                                                                                        Note: Only one of x and x - 1 can be prime, so it is okay that the spliced sequence starts with x - 1. Though the sequence could be open on both sides ([x,-1,-∞]), this would needlessly include x twice in the sequence. So, for sake of "efficiency", I chose the left-closed version (also because I like to show off Tidy).






                                                                                        share|improve this answer









                                                                                        $endgroup$
















                                                                                          3












                                                                                          3








                                                                                          3





                                                                                          $begingroup$


                                                                                          Tidy, 43 bytes



                                                                                          {x:(prime↦splice(]x,-1,-∞],[x,∞]))@0}


                                                                                          Try it online!



                                                                                          Explanation



                                                                                          This is a lambda with parameter x. This works by creating the following sequence:



                                                                                          [x - 1, x, x - 2, x + 1, x - 3, x + 2, x - 4, x + 3, ...]


                                                                                          This is splicing together the two sequences ]x, -1, -∞] (left-closed, right-open) and [x, ∞] (both open).



                                                                                          For x = 80, this looks like:



                                                                                          [79, 80, 78, 81, 77, 82, 76, 83, 75, 84, 74, 85, ...]


                                                                                          Then, we use f↦s to select all elements from s satisfying f. In this case, we filter out all composite numbers, leaving only the prime ones. For the same x, this becomes:



                                                                                          [79, 83, 73, 71, 89, 67, 97, 61, 59, 101, 103, 53, ...]


                                                                                          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 with x - 1 is spliced in first.



                                                                                          Note: Only one of x and x - 1 can be prime, so it is okay that the spliced sequence starts with x - 1. Though the sequence could be open on both sides ([x,-1,-∞]), this would needlessly include x twice in the sequence. So, for sake of "efficiency", I chose the left-closed version (also because I like to show off Tidy).






                                                                                          share|improve this answer









                                                                                          $endgroup$




                                                                                          Tidy, 43 bytes



                                                                                          {x:(prime↦splice(]x,-1,-∞],[x,∞]))@0}


                                                                                          Try it online!



                                                                                          Explanation



                                                                                          This is a lambda with parameter x. This works by creating the following sequence:



                                                                                          [x - 1, x, x - 2, x + 1, x - 3, x + 2, x - 4, x + 3, ...]


                                                                                          This is splicing together the two sequences ]x, -1, -∞] (left-closed, right-open) and [x, ∞] (both open).



                                                                                          For x = 80, this looks like:



                                                                                          [79, 80, 78, 81, 77, 82, 76, 83, 75, 84, 74, 85, ...]


                                                                                          Then, we use f↦s to select all elements from s satisfying f. In this case, we filter out all composite numbers, leaving only the prime ones. For the same x, this becomes:



                                                                                          [79, 83, 73, 71, 89, 67, 97, 61, 59, 101, 103, 53, ...]


                                                                                          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 with x - 1 is spliced in first.



                                                                                          Note: Only one of x and x - 1 can be prime, so it is okay that the spliced sequence starts with x - 1. Though the sequence could be open on both sides ([x,-1,-∞]), this would needlessly include x twice in the sequence. So, for sake of "efficiency", I chose the left-closed version (also because I like to show off Tidy).







                                                                                          share|improve this answer












                                                                                          share|improve this answer



                                                                                          share|improve this answer










                                                                                          answered Mar 27 at 21:39









                                                                                          Conor O'BrienConor O'Brien

                                                                                          30.6k264162




                                                                                          30.6k264162























                                                                                              3












                                                                                              $begingroup$


                                                                                              Python 2, 71 bytes





                                                                                              f=lambda n,k=1,p=1:k<n*3and min(k+n-p%k*2*n,f(n,k+1,p*k*k)-n,key=abs)+n


                                                                                              Try it online!



                                                                                              A recursive function that uses the Wilson's Theorem prime generator. The product p tracks $(k-1)!^2$, and p%k is 1 for primes and 0 for non-primes. To make it easy to compare abs(k-n) for different primes k, we store k-n and compare via abs, adding back n to get the result k.



                                                                                              The expression k+n-p%k*2*n is designed to give k-n on primes (where p%k=1), and otherwise a "bad" value of k+n that's always bigger in absolute value and so doesn't affect the minimum, so that non-primes are passed over.






                                                                                              share|improve this answer









                                                                                              $endgroup$


















                                                                                                3












                                                                                                $begingroup$


                                                                                                Python 2, 71 bytes





                                                                                                f=lambda n,k=1,p=1:k<n*3and min(k+n-p%k*2*n,f(n,k+1,p*k*k)-n,key=abs)+n


                                                                                                Try it online!



                                                                                                A recursive function that uses the Wilson's Theorem prime generator. The product p tracks $(k-1)!^2$, and p%k is 1 for primes and 0 for non-primes. To make it easy to compare abs(k-n) for different primes k, we store k-n and compare via abs, adding back n to get the result k.



                                                                                                The expression k+n-p%k*2*n is designed to give k-n on primes (where p%k=1), and otherwise a "bad" value of k+n that's always bigger in absolute value and so doesn't affect the minimum, so that non-primes are passed over.






                                                                                                share|improve this answer









                                                                                                $endgroup$
















                                                                                                  3












                                                                                                  3








                                                                                                  3





                                                                                                  $begingroup$


                                                                                                  Python 2, 71 bytes





                                                                                                  f=lambda n,k=1,p=1:k<n*3and min(k+n-p%k*2*n,f(n,k+1,p*k*k)-n,key=abs)+n


                                                                                                  Try it online!



                                                                                                  A recursive function that uses the Wilson's Theorem prime generator. The product p tracks $(k-1)!^2$, and p%k is 1 for primes and 0 for non-primes. To make it easy to compare abs(k-n) for different primes k, we store k-n and compare via abs, adding back n to get the result k.



                                                                                                  The expression k+n-p%k*2*n is designed to give k-n on primes (where p%k=1), and otherwise a "bad" value of k+n that's always bigger in absolute value and so doesn't affect the minimum, so that non-primes are passed over.






                                                                                                  share|improve this answer









                                                                                                  $endgroup$




                                                                                                  Python 2, 71 bytes





                                                                                                  f=lambda n,k=1,p=1:k<n*3and min(k+n-p%k*2*n,f(n,k+1,p*k*k)-n,key=abs)+n


                                                                                                  Try it online!



                                                                                                  A recursive function that uses the Wilson's Theorem prime generator. The product p tracks $(k-1)!^2$, and p%k is 1 for primes and 0 for non-primes. To make it easy to compare abs(k-n) for different primes k, we store k-n and compare via abs, adding back n to get the result k.



                                                                                                  The expression k+n-p%k*2*n is designed to give k-n on primes (where p%k=1), and otherwise a "bad" value of k+n that's always bigger in absolute value and so doesn't affect the minimum, so that non-primes are passed over.







                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Mar 28 at 0:04









                                                                                                  xnorxnor

                                                                                                  93.6k18190450




                                                                                                  93.6k18190450























                                                                                                      3












                                                                                                      $begingroup$


                                                                                                      APL (Dyalog Extended), 20 15 bytesSBCS





                                                                                                      Tacit prefix function inspired by Galen Ivanov's J answer.



                                                                                                      ⊢(⊃⍋⍤|⍤-⊇⊢)¯2⍭⍳


                                                                                                      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)






                                                                                                      share|improve this answer











                                                                                                      $endgroup$


















                                                                                                        3












                                                                                                        $begingroup$


                                                                                                        APL (Dyalog Extended), 20 15 bytesSBCS





                                                                                                        Tacit prefix function inspired by Galen Ivanov's J answer.



                                                                                                        ⊢(⊃⍋⍤|⍤-⊇⊢)¯2⍭⍳


                                                                                                        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)






                                                                                                        share|improve this answer











                                                                                                        $endgroup$
















                                                                                                          3












                                                                                                          3








                                                                                                          3





                                                                                                          $begingroup$


                                                                                                          APL (Dyalog Extended), 20 15 bytesSBCS





                                                                                                          Tacit prefix function inspired by Galen Ivanov's J answer.



                                                                                                          ⊢(⊃⍋⍤|⍤-⊇⊢)¯2⍭⍳


                                                                                                          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)






                                                                                                          share|improve this answer











                                                                                                          $endgroup$




                                                                                                          APL (Dyalog Extended), 20 15 bytesSBCS





                                                                                                          Tacit prefix function inspired by Galen Ivanov's J answer.



                                                                                                          ⊢(⊃⍋⍤|⍤-⊇⊢)¯2⍭⍳


                                                                                                          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)







                                                                                                          share|improve this answer














                                                                                                          share|improve this answer



                                                                                                          share|improve this answer








                                                                                                          edited Mar 28 at 23:40

























                                                                                                          answered Mar 27 at 17:23









                                                                                                          AdámAdám

                                                                                                          28.9k276207




                                                                                                          28.9k276207























                                                                                                              3












                                                                                                              $begingroup$


                                                                                                              Perl 6, 35 bytes





                                                                                                              {$_+=($*=-1)*$++until .is-prime;$_}


                                                                                                              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 the until prevents the automagically returned value so there's an extra $_ hanging around.






                                                                                                              share|improve this answer











                                                                                                              $endgroup$













                                                                                                              • $begingroup$
                                                                                                                I'd usually use a sequence operator approach to something like this, but comes out to one byte longer, so nice work finding a shorter method
                                                                                                                $endgroup$
                                                                                                                – Jo King
                                                                                                                Mar 29 at 0:39












                                                                                                              • $begingroup$
                                                                                                                @JoKing good catch. The things that happen when I golf too quickly after getting a working solution. I had a similar one but the damned lack of [-1] haha
                                                                                                                $endgroup$
                                                                                                                – guifa
                                                                                                                Mar 29 at 0:49
















                                                                                                              3












                                                                                                              $begingroup$


                                                                                                              Perl 6, 35 bytes





                                                                                                              {$_+=($*=-1)*$++until .is-prime;$_}


                                                                                                              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 the until prevents the automagically returned value so there's an extra $_ hanging around.






                                                                                                              share|improve this answer











                                                                                                              $endgroup$













                                                                                                              • $begingroup$
                                                                                                                I'd usually use a sequence operator approach to something like this, but comes out to one byte longer, so nice work finding a shorter method
                                                                                                                $endgroup$
                                                                                                                – Jo King
                                                                                                                Mar 29 at 0:39












                                                                                                              • $begingroup$
                                                                                                                @JoKing good catch. The things that happen when I golf too quickly after getting a working solution. I had a similar one but the damned lack of [-1] haha
                                                                                                                $endgroup$
                                                                                                                – guifa
                                                                                                                Mar 29 at 0:49














                                                                                                              3












                                                                                                              3








                                                                                                              3





                                                                                                              $begingroup$


                                                                                                              Perl 6, 35 bytes





                                                                                                              {$_+=($*=-1)*$++until .is-prime;$_}


                                                                                                              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 the until prevents the automagically returned value so there's an extra $_ hanging around.






                                                                                                              share|improve this answer











                                                                                                              $endgroup$




                                                                                                              Perl 6, 35 bytes





                                                                                                              {$_+=($*=-1)*$++until .is-prime;$_}


                                                                                                              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 the until prevents the automagically returned value so there's an extra $_ hanging around.







                                                                                                              share|improve this answer














                                                                                                              share|improve this answer



                                                                                                              share|improve this answer








                                                                                                              edited Mar 29 at 0:51

























                                                                                                              answered Mar 29 at 0:15









                                                                                                              guifaguifa

                                                                                                              28115




                                                                                                              28115












                                                                                                              • $begingroup$
                                                                                                                I'd usually use a sequence operator approach to something like this, but comes out to one byte longer, so nice work finding a shorter method
                                                                                                                $endgroup$
                                                                                                                – Jo King
                                                                                                                Mar 29 at 0:39












                                                                                                              • $begingroup$
                                                                                                                @JoKing good catch. The things that happen when I golf too quickly after getting a working solution. I had a similar one but the damned lack of [-1] haha
                                                                                                                $endgroup$
                                                                                                                – guifa
                                                                                                                Mar 29 at 0:49


















                                                                                                              • $begingroup$
                                                                                                                I'd usually use a sequence operator approach to something like this, but comes out to one byte longer, so nice work finding a shorter method
                                                                                                                $endgroup$
                                                                                                                – Jo King
                                                                                                                Mar 29 at 0:39












                                                                                                              • $begingroup$
                                                                                                                @JoKing good catch. The things that happen when I golf too quickly after getting a working solution. I had a similar one but the damned lack of [-1] haha
                                                                                                                $endgroup$
                                                                                                                – guifa
                                                                                                                Mar 29 at 0:49
















                                                                                                              $begingroup$
                                                                                                              I'd usually use a sequence operator approach to something like this, but comes out to one byte longer, so nice work finding a shorter method
                                                                                                              $endgroup$
                                                                                                              – Jo King
                                                                                                              Mar 29 at 0:39






                                                                                                              $begingroup$
                                                                                                              I'd usually use a sequence operator approach to something like this, but comes out to one byte longer, so nice work finding a shorter method
                                                                                                              $endgroup$
                                                                                                              – Jo King
                                                                                                              Mar 29 at 0:39














                                                                                                              $begingroup$
                                                                                                              @JoKing good catch. The things that happen when I golf too quickly after getting a working solution. I had a similar one but the damned lack of [-1] haha
                                                                                                              $endgroup$
                                                                                                              – guifa
                                                                                                              Mar 29 at 0:49




                                                                                                              $begingroup$
                                                                                                              @JoKing good catch. The things that happen when I golf too quickly after getting a working solution. I had a similar one but the damned lack of [-1] haha
                                                                                                              $endgroup$
                                                                                                              – guifa
                                                                                                              Mar 29 at 0:49











                                                                                                              3












                                                                                                              $begingroup$

                                                                                                              C, 122 121 104 bytes





                                                                                                              p(a,i){for(i=1;++i<a;)if(a%i<1)return 0;return a>1;}c(a,b){for(b=a;;b++)if(p(--a)|p(b))return p(b)?b:a;}


                                                                                                              Use it calling function c() and passing as argument the number; it should return the closest prime.



                                                                                                              Thanks to Embodiment of Ignorance for 1 byte saved a big improvement.



                                                                                                              Try it online!






                                                                                                              share|improve this answer











                                                                                                              $endgroup$













                                                                                                              • $begingroup$
                                                                                                                But c() receives two parameters... Also, you can probably shorten the while(1) to for(;;) (untested, since I don't get how to run your code
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 5:03










                                                                                                              • $begingroup$
                                                                                                                @EmbodimentofIgnorance I wrote it and tested it all on an online c compiler, I could call c() passing only the first parameter. And you are right, for(;;) saves me a byte, only 117 left to get first place :)
                                                                                                                $endgroup$
                                                                                                                – Lince Assassino
                                                                                                                Mar 28 at 11:30












                                                                                                              • $begingroup$
                                                                                                                110 bytes: #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/…
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 21:06










                                                                                                              • $begingroup$
                                                                                                                106: tio.run/…
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 21:12












                                                                                                              • $begingroup$
                                                                                                                101: tio.run/…
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 21:17


















                                                                                                              3












                                                                                                              $begingroup$

                                                                                                              C, 122 121 104 bytes





                                                                                                              p(a,i){for(i=1;++i<a;)if(a%i<1)return 0;return a>1;}c(a,b){for(b=a;;b++)if(p(--a)|p(b))return p(b)?b:a;}


                                                                                                              Use it calling function c() and passing as argument the number; it should return the closest prime.



                                                                                                              Thanks to Embodiment of Ignorance for 1 byte saved a big improvement.



                                                                                                              Try it online!






                                                                                                              share|improve this answer











                                                                                                              $endgroup$













                                                                                                              • $begingroup$
                                                                                                                But c() receives two parameters... Also, you can probably shorten the while(1) to for(;;) (untested, since I don't get how to run your code
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 5:03










                                                                                                              • $begingroup$
                                                                                                                @EmbodimentofIgnorance I wrote it and tested it all on an online c compiler, I could call c() passing only the first parameter. And you are right, for(;;) saves me a byte, only 117 left to get first place :)
                                                                                                                $endgroup$
                                                                                                                – Lince Assassino
                                                                                                                Mar 28 at 11:30












                                                                                                              • $begingroup$
                                                                                                                110 bytes: #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/…
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 21:06










                                                                                                              • $begingroup$
                                                                                                                106: tio.run/…
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 21:12












                                                                                                              • $begingroup$
                                                                                                                101: tio.run/…
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 21:17
















                                                                                                              3












                                                                                                              3








                                                                                                              3





                                                                                                              $begingroup$

                                                                                                              C, 122 121 104 bytes





                                                                                                              p(a,i){for(i=1;++i<a;)if(a%i<1)return 0;return a>1;}c(a,b){for(b=a;;b++)if(p(--a)|p(b))return p(b)?b:a;}


                                                                                                              Use it calling function c() and passing as argument the number; it should return the closest prime.



                                                                                                              Thanks to Embodiment of Ignorance for 1 byte saved a big improvement.



                                                                                                              Try it online!






                                                                                                              share|improve this answer











                                                                                                              $endgroup$



                                                                                                              C, 122 121 104 bytes





                                                                                                              p(a,i){for(i=1;++i<a;)if(a%i<1)return 0;return a>1;}c(a,b){for(b=a;;b++)if(p(--a)|p(b))return p(b)?b:a;}


                                                                                                              Use it calling function c() and passing as argument the number; it should return the closest prime.



                                                                                                              Thanks to Embodiment of Ignorance for 1 byte saved a big improvement.



                                                                                                              Try it online!







                                                                                                              share|improve this answer














                                                                                                              share|improve this answer



                                                                                                              share|improve this answer








                                                                                                              edited Mar 29 at 17:22

























                                                                                                              answered Mar 27 at 20:24









                                                                                                              Lince AssassinoLince Assassino

                                                                                                              1114




                                                                                                              1114












                                                                                                              • $begingroup$
                                                                                                                But c() receives two parameters... Also, you can probably shorten the while(1) to for(;;) (untested, since I don't get how to run your code
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 5:03










                                                                                                              • $begingroup$
                                                                                                                @EmbodimentofIgnorance I wrote it and tested it all on an online c compiler, I could call c() passing only the first parameter. And you are right, for(;;) saves me a byte, only 117 left to get first place :)
                                                                                                                $endgroup$
                                                                                                                – Lince Assassino
                                                                                                                Mar 28 at 11:30












                                                                                                              • $begingroup$
                                                                                                                110 bytes: #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/…
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 21:06










                                                                                                              • $begingroup$
                                                                                                                106: tio.run/…
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 21:12












                                                                                                              • $begingroup$
                                                                                                                101: tio.run/…
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 21:17




















                                                                                                              • $begingroup$
                                                                                                                But c() receives two parameters... Also, you can probably shorten the while(1) to for(;;) (untested, since I don't get how to run your code
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 5:03










                                                                                                              • $begingroup$
                                                                                                                @EmbodimentofIgnorance I wrote it and tested it all on an online c compiler, I could call c() passing only the first parameter. And you are right, for(;;) saves me a byte, only 117 left to get first place :)
                                                                                                                $endgroup$
                                                                                                                – Lince Assassino
                                                                                                                Mar 28 at 11:30












                                                                                                              • $begingroup$
                                                                                                                110 bytes: #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/…
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 21:06










                                                                                                              • $begingroup$
                                                                                                                106: tio.run/…
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 21:12












                                                                                                              • $begingroup$
                                                                                                                101: tio.run/…
                                                                                                                $endgroup$
                                                                                                                – Embodiment of Ignorance
                                                                                                                Mar 28 at 21:17


















                                                                                                              $begingroup$
                                                                                                              But c() receives two parameters... Also, you can probably shorten the while(1) to for(;;) (untested, since I don't get how to run your code
                                                                                                              $endgroup$
                                                                                                              – Embodiment of Ignorance
                                                                                                              Mar 28 at 5:03




                                                                                                              $begingroup$
                                                                                                              But c() receives two parameters... Also, you can probably shorten the while(1) to for(;;) (untested, since I don't get how to run your code
                                                                                                              $endgroup$
                                                                                                              – Embodiment of Ignorance
                                                                                                              Mar 28 at 5:03












                                                                                                              $begingroup$
                                                                                                              @EmbodimentofIgnorance I wrote it and tested it all on an online c compiler, I could call c() passing only the first parameter. And you are right, for(;;) saves me a byte, only 117 left to get first place :)
                                                                                                              $endgroup$
                                                                                                              – Lince Assassino
                                                                                                              Mar 28 at 11:30






                                                                                                              $begingroup$
                                                                                                              @EmbodimentofIgnorance I wrote it and tested it all on an online c compiler, I could call c() passing only the first parameter. And you are right, for(;;) saves me a byte, only 117 left to get first place :)
                                                                                                              $endgroup$
                                                                                                              – Lince Assassino
                                                                                                              Mar 28 at 11:30














                                                                                                              $begingroup$
                                                                                                              110 bytes: #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/…
                                                                                                              $endgroup$
                                                                                                              – Embodiment of Ignorance
                                                                                                              Mar 28 at 21:06




                                                                                                              $begingroup$
                                                                                                              110 bytes: #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/…
                                                                                                              $endgroup$
                                                                                                              – Embodiment of Ignorance
                                                                                                              Mar 28 at 21:06












                                                                                                              $begingroup$
                                                                                                              106: tio.run/…
                                                                                                              $endgroup$
                                                                                                              – Embodiment of Ignorance
                                                                                                              Mar 28 at 21:12






                                                                                                              $begingroup$
                                                                                                              106: tio.run/…
                                                                                                              $endgroup$
                                                                                                              – Embodiment of Ignorance
                                                                                                              Mar 28 at 21:12














                                                                                                              $begingroup$
                                                                                                              101: tio.run/…
                                                                                                              $endgroup$
                                                                                                              – Embodiment of Ignorance
                                                                                                              Mar 28 at 21:17






                                                                                                              $begingroup$
                                                                                                              101: tio.run/…
                                                                                                              $endgroup$
                                                                                                              – Embodiment of Ignorance
                                                                                                              Mar 28 at 21:17













                                                                                                              3












                                                                                                              $begingroup$


                                                                                                              Wolfram Language (Mathematica), 52 bytes



                                                                                                              If[PrimeQ[s=#],s,#&@@Nearest[s~NextPrime~{-1,1},s]]&


                                                                                                              Try it online!






                                                                                                              share|improve this answer











                                                                                                              $endgroup$













                                                                                                              • $begingroup$
                                                                                                                You have an extra space that can be removed to save a byte.
                                                                                                                $endgroup$
                                                                                                                – Ben
                                                                                                                Mar 29 at 16:03










                                                                                                              • $begingroup$
                                                                                                                @Ben you are right. thanx
                                                                                                                $endgroup$
                                                                                                                – J42161217
                                                                                                                Mar 29 at 23:08
















                                                                                                              3












                                                                                                              $begingroup$


                                                                                                              Wolfram Language (Mathematica), 52 bytes



                                                                                                              If[PrimeQ[s=#],s,#&@@Nearest[s~NextPrime~{-1,1},s]]&


                                                                                                              Try it online!






                                                                                                              share|improve this answer











                                                                                                              $endgroup$













                                                                                                              • $begingroup$
                                                                                                                You have an extra space that can be removed to save a byte.
                                                                                                                $endgroup$
                                                                                                                – Ben
                                                                                                                Mar 29 at 16:03










                                                                                                              • $begingroup$
                                                                                                                @Ben you are right. thanx
                                                                                                                $endgroup$
                                                                                                                – J42161217
                                                                                                                Mar 29 at 23:08














                                                                                                              3












                                                                                                              3








                                                                                                              3





                                                                                                              $begingroup$


                                                                                                              Wolfram Language (Mathematica), 52 bytes



                                                                                                              If[PrimeQ[s=#],s,#&@@Nearest[s~NextPrime~{-1,1},s]]&


                                                                                                              Try it online!






                                                                                                              share|improve this answer











                                                                                                              $endgroup$




                                                                                                              Wolfram Language (Mathematica), 52 bytes



                                                                                                              If[PrimeQ[s=#],s,#&@@Nearest[s~NextPrime~{-1,1},s]]&


                                                                                                              Try it online!







                                                                                                              share|improve this answer














                                                                                                              share|improve this answer



                                                                                                              share|improve this answer








                                                                                                              edited Mar 29 at 23:09

























                                                                                                              answered Mar 27 at 15:32









                                                                                                              J42161217J42161217

                                                                                                              13.9k21353




                                                                                                              13.9k21353












                                                                                                              • $begingroup$
                                                                                                                You have an extra space that can be removed to save a byte.
                                                                                                                $endgroup$
                                                                                                                – Ben
                                                                                                                Mar 29 at 16:03










                                                                                                              • $begingroup$
                                                                                                                @Ben you are right. thanx
                                                                                                                $endgroup$
                                                                                                                – J42161217
                                                                                                                Mar 29 at 23:08


















                                                                                                              • $begingroup$
                                                                                                                You have an extra space that can be removed to save a byte.
                                                                                                                $endgroup$
                                                                                                                – Ben
                                                                                                                Mar 29 at 16:03










                                                                                                              • $begingroup$
                                                                                                                @Ben you are right. thanx
                                                                                                                $endgroup$
                                                                                                                – J42161217
                                                                                                                Mar 29 at 23:08
















                                                                                                              $begingroup$
                                                                                                              You have an extra space that can be removed to save a byte.
                                                                                                              $endgroup$
                                                                                                              – Ben
                                                                                                              Mar 29 at 16:03




                                                                                                              $begingroup$
                                                                                                              You have an extra space that can be removed to save a byte.
                                                                                                              $endgroup$
                                                                                                              – Ben
                                                                                                              Mar 29 at 16:03












                                                                                                              $begingroup$
                                                                                                              @Ben you are right. thanx
                                                                                                              $endgroup$
                                                                                                              – J42161217
                                                                                                              Mar 29 at 23:08




                                                                                                              $begingroup$
                                                                                                              @Ben you are right. thanx
                                                                                                              $endgroup$
                                                                                                              – J42161217
                                                                                                              Mar 29 at 23:08











                                                                                                              2












                                                                                                              $begingroup$

                                                                                                              APL(NARS), 38 chars, 76 bytes



                                                                                                              {⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}


                                                                                                              0π is the test for prime, ¯1π the prev prime, 1π is the next prime; test:



                                                                                                                f←{⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}
                                                                                                              f¨80 100 5 9 532 1
                                                                                                              79 101 5 7 523 2





                                                                                                              share|improve this answer









                                                                                                              $endgroup$


















                                                                                                                2












                                                                                                                $begingroup$

                                                                                                                APL(NARS), 38 chars, 76 bytes



                                                                                                                {⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}


                                                                                                                0π is the test for prime, ¯1π the prev prime, 1π is the next prime; test:



                                                                                                                  f←{⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}
                                                                                                                f¨80 100 5 9 532 1
                                                                                                                79 101 5 7 523 2





                                                                                                                share|improve this answer









                                                                                                                $endgroup$
















                                                                                                                  2












                                                                                                                  2








                                                                                                                  2





                                                                                                                  $begingroup$

                                                                                                                  APL(NARS), 38 chars, 76 bytes



                                                                                                                  {⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}


                                                                                                                  0π is the test for prime, ¯1π the prev prime, 1π is the next prime; test:



                                                                                                                    f←{⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}
                                                                                                                  f¨80 100 5 9 532 1
                                                                                                                  79 101 5 7 523 2





                                                                                                                  share|improve this answer









                                                                                                                  $endgroup$



                                                                                                                  APL(NARS), 38 chars, 76 bytes



                                                                                                                  {⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}


                                                                                                                  0π is the test for prime, ¯1π the prev prime, 1π is the next prime; test:



                                                                                                                    f←{⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}
                                                                                                                  f¨80 100 5 9 532 1
                                                                                                                  79 101 5 7 523 2






                                                                                                                  share|improve this answer












                                                                                                                  share|improve this answer



                                                                                                                  share|improve this answer










                                                                                                                  answered Mar 27 at 18:05









                                                                                                                  RosLuPRosLuP

                                                                                                                  2,296514




                                                                                                                  2,296514























                                                                                                                      2












                                                                                                                      $begingroup$


                                                                                                                      J, 19 15 bytes



                                                                                                                      (0{]/:|@-)p:@i.


                                                                                                                      Try it online!






                                                                                                                      share|improve this answer











                                                                                                                      $endgroup$


















                                                                                                                        2












                                                                                                                        $begingroup$


                                                                                                                        J, 19 15 bytes



                                                                                                                        (0{]/:|@-)p:@i.


                                                                                                                        Try it online!






                                                                                                                        share|improve this answer











                                                                                                                        $endgroup$
















                                                                                                                          2












                                                                                                                          2








                                                                                                                          2





                                                                                                                          $begingroup$


                                                                                                                          J, 19 15 bytes



                                                                                                                          (0{]/:|@-)p:@i.


                                                                                                                          Try it online!






                                                                                                                          share|improve this answer











                                                                                                                          $endgroup$




                                                                                                                          J, 19 15 bytes



                                                                                                                          (0{]/:|@-)p:@i.


                                                                                                                          Try it online!







                                                                                                                          share|improve this answer














                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer








                                                                                                                          edited Mar 27 at 22:52

























                                                                                                                          answered Mar 27 at 20:28









                                                                                                                          Galen IvanovGalen Ivanov

                                                                                                                          7,41211034




                                                                                                                          7,41211034























                                                                                                                              2












                                                                                                                              $begingroup$


                                                                                                                              Perl 5, 59 bytes





                                                                                                                              $a=0;while((1x$_)=~/^.?$|^(..+?)1+$/){$_+=(-1)**$a*($a++)}


                                                                                                                              Try it online!



                                                                                                                              /^.?$|^(..+?)1+$/ is tricky regexp to check prime



                                                                                                                              (-1)**$a*($a++) generate sequence 0,-1, 2,-3 ...






                                                                                                                              share|improve this answer









                                                                                                                              $endgroup$


















                                                                                                                                2












                                                                                                                                $begingroup$


                                                                                                                                Perl 5, 59 bytes





                                                                                                                                $a=0;while((1x$_)=~/^.?$|^(..+?)1+$/){$_+=(-1)**$a*($a++)}


                                                                                                                                Try it online!



                                                                                                                                /^.?$|^(..+?)1+$/ is tricky regexp to check prime



                                                                                                                                (-1)**$a*($a++) generate sequence 0,-1, 2,-3 ...






                                                                                                                                share|improve this answer









                                                                                                                                $endgroup$
















                                                                                                                                  2












                                                                                                                                  2








                                                                                                                                  2





                                                                                                                                  $begingroup$


                                                                                                                                  Perl 5, 59 bytes





                                                                                                                                  $a=0;while((1x$_)=~/^.?$|^(..+?)1+$/){$_+=(-1)**$a*($a++)}


                                                                                                                                  Try it online!



                                                                                                                                  /^.?$|^(..+?)1+$/ is tricky regexp to check prime



                                                                                                                                  (-1)**$a*($a++) generate sequence 0,-1, 2,-3 ...






                                                                                                                                  share|improve this answer









                                                                                                                                  $endgroup$




                                                                                                                                  Perl 5, 59 bytes





                                                                                                                                  $a=0;while((1x$_)=~/^.?$|^(..+?)1+$/){$_+=(-1)**$a*($a++)}


                                                                                                                                  Try it online!



                                                                                                                                  /^.?$|^(..+?)1+$/ is tricky regexp to check prime



                                                                                                                                  (-1)**$a*($a++) generate sequence 0,-1, 2,-3 ...







                                                                                                                                  share|improve this answer












                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer










                                                                                                                                  answered Mar 28 at 8:35









                                                                                                                                  VeitcelVeitcel

                                                                                                                                  613




                                                                                                                                  613























                                                                                                                                      2












                                                                                                                                      $begingroup$


                                                                                                                                      MathGolf, 10 bytes



                                                                                                                                      ∞╒g¶áÅ-±├Þ


                                                                                                                                      Try it online.



                                                                                                                                      Explanation:





                                                                                                                                      ∞            # Double the (implicit) input-integer
                                                                                                                                      ╒ # Create a list in the range [1, 2*n]
                                                                                                                                      g¶ # Filter so only the prime numbers remain
                                                                                                                                      áÅ # Sort this list using the next two character:
                                                                                                                                      -± # The absolute difference with the (implicit) input-integer
                                                                                                                                      ├ # Push the first item of the list
                                                                                                                                      # (unfortunately without popping the list itself, so:)
                                                                                                                                      Þ # Discard everything from the stack except for the top
                                                                                                                                      # (which is output implicitly as result)





                                                                                                                                      share|improve this answer











                                                                                                                                      $endgroup$













                                                                                                                                      • $begingroup$
                                                                                                                                        @JoKing Thanks! I knew Max thought about changing it, but didn't knew he actually did. The docs still state the old one.
                                                                                                                                        $endgroup$
                                                                                                                                        – Kevin Cruijssen
                                                                                                                                        Mar 28 at 8:53










                                                                                                                                      • $begingroup$
                                                                                                                                        Ah, I use the mathgolf.txt file as reference, since it seems to be more up to date
                                                                                                                                        $endgroup$
                                                                                                                                        – Jo King
                                                                                                                                        Mar 28 at 23:21










                                                                                                                                      • $begingroup$
                                                                                                                                        @JoKing Yeah, he told me yesterday about that file as well. Will use it from now on. :)
                                                                                                                                        $endgroup$
                                                                                                                                        – Kevin Cruijssen
                                                                                                                                        Mar 29 at 7:23
















                                                                                                                                      2












                                                                                                                                      $begingroup$


                                                                                                                                      MathGolf, 10 bytes



                                                                                                                                      ∞╒g¶áÅ-±├Þ


                                                                                                                                      Try it online.



                                                                                                                                      Explanation:





                                                                                                                                      ∞            # Double the (implicit) input-integer
                                                                                                                                      ╒ # Create a list in the range [1, 2*n]
                                                                                                                                      g¶ # Filter so only the prime numbers remain
                                                                                                                                      áÅ # Sort this list using the next two character:
                                                                                                                                      -± # The absolute difference with the (implicit) input-integer
                                                                                                                                      ├ # Push the first item of the list
                                                                                                                                      # (unfortunately without popping the list itself, so:)
                                                                                                                                      Þ # Discard everything from the stack except for the top
                                                                                                                                      # (which is output implicitly as result)





                                                                                                                                      share|improve this answer











                                                                                                                                      $endgroup$













                                                                                                                                      • $begingroup$
                                                                                                                                        @JoKing Thanks! I knew Max thought about changing it, but didn't knew he actually did. The docs still state the old one.
                                                                                                                                        $endgroup$
                                                                                                                                        – Kevin Cruijssen
                                                                                                                                        Mar 28 at 8:53










                                                                                                                                      • $begingroup$
                                                                                                                                        Ah, I use the mathgolf.txt file as reference, since it seems to be more up to date
                                                                                                                                        $endgroup$
                                                                                                                                        – Jo King
                                                                                                                                        Mar 28 at 23:21










                                                                                                                                      • $begingroup$
                                                                                                                                        @JoKing Yeah, he told me yesterday about that file as well. Will use it from now on. :)
                                                                                                                                        $endgroup$
                                                                                                                                        – Kevin Cruijssen
                                                                                                                                        Mar 29 at 7:23














                                                                                                                                      2












                                                                                                                                      2








                                                                                                                                      2





                                                                                                                                      $begingroup$


                                                                                                                                      MathGolf, 10 bytes



                                                                                                                                      ∞╒g¶áÅ-±├Þ


                                                                                                                                      Try it online.



                                                                                                                                      Explanation:





                                                                                                                                      ∞            # Double the (implicit) input-integer
                                                                                                                                      ╒ # Create a list in the range [1, 2*n]
                                                                                                                                      g¶ # Filter so only the prime numbers remain
                                                                                                                                      áÅ # Sort this list using the next two character:
                                                                                                                                      -± # The absolute difference with the (implicit) input-integer
                                                                                                                                      ├ # Push the first item of the list
                                                                                                                                      # (unfortunately without popping the list itself, so:)
                                                                                                                                      Þ # Discard everything from the stack except for the top
                                                                                                                                      # (which is output implicitly as result)





                                                                                                                                      share|improve this answer











                                                                                                                                      $endgroup$




                                                                                                                                      MathGolf, 10 bytes



                                                                                                                                      ∞╒g¶áÅ-±├Þ


                                                                                                                                      Try it online.



                                                                                                                                      Explanation:





                                                                                                                                      ∞            # Double the (implicit) input-integer
                                                                                                                                      ╒ # Create a list in the range [1, 2*n]
                                                                                                                                      g¶ # Filter so only the prime numbers remain
                                                                                                                                      áÅ # Sort this list using the next two character:
                                                                                                                                      -± # The absolute difference with the (implicit) input-integer
                                                                                                                                      ├ # Push the first item of the list
                                                                                                                                      # (unfortunately without popping the list itself, so:)
                                                                                                                                      Þ # Discard everything from the stack except for the top
                                                                                                                                      # (which is output implicitly as result)






                                                                                                                                      share|improve this answer














                                                                                                                                      share|improve this answer



                                                                                                                                      share|improve this answer








                                                                                                                                      edited Mar 28 at 8:52

























                                                                                                                                      answered Mar 28 at 8:43









                                                                                                                                      Kevin CruijssenKevin Cruijssen

                                                                                                                                      42.4k570217




                                                                                                                                      42.4k570217












                                                                                                                                      • $begingroup$
                                                                                                                                        @JoKing Thanks! I knew Max thought about changing it, but didn't knew he actually did. The docs still state the old one.
                                                                                                                                        $endgroup$
                                                                                                                                        – Kevin Cruijssen
                                                                                                                                        Mar 28 at 8:53










                                                                                                                                      • $begingroup$
                                                                                                                                        Ah, I use the mathgolf.txt file as reference, since it seems to be more up to date
                                                                                                                                        $endgroup$
                                                                                                                                        – Jo King
                                                                                                                                        Mar 28 at 23:21










                                                                                                                                      • $begingroup$
                                                                                                                                        @JoKing Yeah, he told me yesterday about that file as well. Will use it from now on. :)
                                                                                                                                        $endgroup$
                                                                                                                                        – Kevin Cruijssen
                                                                                                                                        Mar 29 at 7:23


















                                                                                                                                      • $begingroup$
                                                                                                                                        @JoKing Thanks! I knew Max thought about changing it, but didn't knew he actually did. The docs still state the old one.
                                                                                                                                        $endgroup$
                                                                                                                                        – Kevin Cruijssen
                                                                                                                                        Mar 28 at 8:53










                                                                                                                                      • $begingroup$
                                                                                                                                        Ah, I use the mathgolf.txt file as reference, since it seems to be more up to date
                                                                                                                                        $endgroup$
                                                                                                                                        – Jo King
                                                                                                                                        Mar 28 at 23:21










                                                                                                                                      • $begingroup$
                                                                                                                                        @JoKing Yeah, he told me yesterday about that file as well. Will use it from now on. :)
                                                                                                                                        $endgroup$
                                                                                                                                        – Kevin Cruijssen
                                                                                                                                        Mar 29 at 7:23
















                                                                                                                                      $begingroup$
                                                                                                                                      @JoKing Thanks! I knew Max thought about changing it, but didn't knew he actually did. The docs still state the old one.
                                                                                                                                      $endgroup$
                                                                                                                                      – Kevin Cruijssen
                                                                                                                                      Mar 28 at 8:53




                                                                                                                                      $begingroup$
                                                                                                                                      @JoKing Thanks! I knew Max thought about changing it, but didn't knew he actually did. The docs still state the old one.
                                                                                                                                      $endgroup$
                                                                                                                                      – Kevin Cruijssen
                                                                                                                                      Mar 28 at 8:53












                                                                                                                                      $begingroup$
                                                                                                                                      Ah, I use the mathgolf.txt file as reference, since it seems to be more up to date
                                                                                                                                      $endgroup$
                                                                                                                                      – Jo King
                                                                                                                                      Mar 28 at 23:21




                                                                                                                                      $begingroup$
                                                                                                                                      Ah, I use the mathgolf.txt file as reference, since it seems to be more up to date
                                                                                                                                      $endgroup$
                                                                                                                                      – Jo King
                                                                                                                                      Mar 28 at 23:21












                                                                                                                                      $begingroup$
                                                                                                                                      @JoKing Yeah, he told me yesterday about that file as well. Will use it from now on. :)
                                                                                                                                      $endgroup$
                                                                                                                                      – Kevin Cruijssen
                                                                                                                                      Mar 29 at 7:23




                                                                                                                                      $begingroup$
                                                                                                                                      @JoKing Yeah, he told me yesterday about that file as well. Will use it from now on. :)
                                                                                                                                      $endgroup$
                                                                                                                                      – Kevin Cruijssen
                                                                                                                                      Mar 29 at 7:23











                                                                                                                                      2












                                                                                                                                      $begingroup$


                                                                                                                                      Factor, 91 bytes



                                                                                                                                      : p ( x -- x ) [ nprimes ] keep dupd [ - abs ] curry map swap zip natural-sort first last ;


                                                                                                                                      Try it online!






                                                                                                                                      share|improve this answer









                                                                                                                                      $endgroup$


















                                                                                                                                        2












                                                                                                                                        $begingroup$


                                                                                                                                        Factor, 91 bytes



                                                                                                                                        : p ( x -- x ) [ nprimes ] keep dupd [ - abs ] curry map swap zip natural-sort first last ;


                                                                                                                                        Try it online!






                                                                                                                                        share|improve this answer









                                                                                                                                        $endgroup$
















                                                                                                                                          2












                                                                                                                                          2








                                                                                                                                          2





                                                                                                                                          $begingroup$


                                                                                                                                          Factor, 91 bytes



                                                                                                                                          : p ( x -- x ) [ nprimes ] keep dupd [ - abs ] curry map swap zip natural-sort first last ;


                                                                                                                                          Try it online!






                                                                                                                                          share|improve this answer









                                                                                                                                          $endgroup$




                                                                                                                                          Factor, 91 bytes



                                                                                                                                          : p ( x -- x ) [ nprimes ] keep dupd [ - abs ] curry map swap zip natural-sort first last ;


                                                                                                                                          Try it online!







                                                                                                                                          share|improve this answer












                                                                                                                                          share|improve this answer



                                                                                                                                          share|improve this answer










                                                                                                                                          answered Mar 28 at 9:41









                                                                                                                                          Galen IvanovGalen Ivanov

                                                                                                                                          7,41211034




                                                                                                                                          7,41211034























                                                                                                                                              2












                                                                                                                                              $begingroup$


                                                                                                                                              Python 2 (Cython), 96 bytes





                                                                                                                                              l=lambda p:min(filter(lambda p:all(p%n for n in range(2,p)),range(2,p*3)),key=lambda x:abs(x-p))


                                                                                                                                              Try it online!






                                                                                                                                              share|improve this answer











                                                                                                                                              $endgroup$













                                                                                                                                              • $begingroup$
                                                                                                                                                Might be able to save a couple bytes via r=range;...
                                                                                                                                                $endgroup$
                                                                                                                                                – Skyler
                                                                                                                                                Mar 28 at 20:33






                                                                                                                                              • 1




                                                                                                                                                $begingroup$
                                                                                                                                                @Arnauld, it now works for x=1
                                                                                                                                                $endgroup$
                                                                                                                                                – Snaddyvitch Dispenser
                                                                                                                                                Mar 29 at 8:20
















                                                                                                                                              2












                                                                                                                                              $begingroup$


                                                                                                                                              Python 2 (Cython), 96 bytes





                                                                                                                                              l=lambda p:min(filter(lambda p:all(p%n for n in range(2,p)),range(2,p*3)),key=lambda x:abs(x-p))


                                                                                                                                              Try it online!






                                                                                                                                              share|improve this answer











                                                                                                                                              $endgroup$













                                                                                                                                              • $begingroup$
                                                                                                                                                Might be able to save a couple bytes via r=range;...
                                                                                                                                                $endgroup$
                                                                                                                                                – Skyler
                                                                                                                                                Mar 28 at 20:33






                                                                                                                                              • 1




                                                                                                                                                $begingroup$
                                                                                                                                                @Arnauld, it now works for x=1
                                                                                                                                                $endgroup$
                                                                                                                                                – Snaddyvitch Dispenser
                                                                                                                                                Mar 29 at 8:20














                                                                                                                                              2












                                                                                                                                              2








                                                                                                                                              2





                                                                                                                                              $begingroup$


                                                                                                                                              Python 2 (Cython), 96 bytes





                                                                                                                                              l=lambda p:min(filter(lambda p:all(p%n for n in range(2,p)),range(2,p*3)),key=lambda x:abs(x-p))


                                                                                                                                              Try it online!






                                                                                                                                              share|improve this answer











                                                                                                                                              $endgroup$




                                                                                                                                              Python 2 (Cython), 96 bytes





                                                                                                                                              l=lambda p:min(filter(lambda p:all(p%n for n in range(2,p)),range(2,p*3)),key=lambda x:abs(x-p))


                                                                                                                                              Try it online!







                                                                                                                                              share|improve this answer














                                                                                                                                              share|improve this answer



                                                                                                                                              share|improve this answer








                                                                                                                                              edited Mar 29 at 8:19

























                                                                                                                                              answered Mar 27 at 16:29









                                                                                                                                              Snaddyvitch DispenserSnaddyvitch Dispenser

                                                                                                                                              1015




                                                                                                                                              1015












                                                                                                                                              • $begingroup$
                                                                                                                                                Might be able to save a couple bytes via r=range;...
                                                                                                                                                $endgroup$
                                                                                                                                                – Skyler
                                                                                                                                                Mar 28 at 20:33






                                                                                                                                              • 1




                                                                                                                                                $begingroup$
                                                                                                                                                @Arnauld, it now works for x=1
                                                                                                                                                $endgroup$
                                                                                                                                                – Snaddyvitch Dispenser
                                                                                                                                                Mar 29 at 8:20


















                                                                                                                                              • $begingroup$
                                                                                                                                                Might be able to save a couple bytes via r=range;...
                                                                                                                                                $endgroup$
                                                                                                                                                – Skyler
                                                                                                                                                Mar 28 at 20:33






                                                                                                                                              • 1




                                                                                                                                                $begingroup$
                                                                                                                                                @Arnauld, it now works for x=1
                                                                                                                                                $endgroup$
                                                                                                                                                – Snaddyvitch Dispenser
                                                                                                                                                Mar 29 at 8:20
















                                                                                                                                              $begingroup$
                                                                                                                                              Might be able to save a couple bytes via r=range;...
                                                                                                                                              $endgroup$
                                                                                                                                              – Skyler
                                                                                                                                              Mar 28 at 20:33




                                                                                                                                              $begingroup$
                                                                                                                                              Might be able to save a couple bytes via r=range;...
                                                                                                                                              $endgroup$
                                                                                                                                              – Skyler
                                                                                                                                              Mar 28 at 20:33




                                                                                                                                              1




                                                                                                                                              1




                                                                                                                                              $begingroup$
                                                                                                                                              @Arnauld, it now works for x=1
                                                                                                                                              $endgroup$
                                                                                                                                              – Snaddyvitch Dispenser
                                                                                                                                              Mar 29 at 8:20




                                                                                                                                              $begingroup$
                                                                                                                                              @Arnauld, it now works for x=1
                                                                                                                                              $endgroup$
                                                                                                                                              – Snaddyvitch Dispenser
                                                                                                                                              Mar 29 at 8:20











                                                                                                                                              2












                                                                                                                                              $begingroup$


                                                                                                                                              C# (Visual C# Interactive Compiler), 104 100 bytes



                                                                                                                                              n=>{int r=0,t=0,m=n;while(r!=2){n+=(n<m)?t:-t;t++;r=0;for(int i=1;i<=n;i++)if(n%i==0)r++;}return n;}


                                                                                                                                              Try it online!



                                                                                                                                              Explanation:



                                                                                                                                              int f(int n)
                                                                                                                                              {
                                                                                                                                              int r = 0; //stores the amount of factors of "n"
                                                                                                                                              int t = 0; //increment used to cover all the integers surrounding "n"
                                                                                                                                              int m = n; //placeholder to toggle between adding or substracting "t" to "n"

                                                                                                                                              while (r != 2) //while the amount of factors found for "n" is different to 2 ("1" + itself)
                                                                                                                                              {
                                                                                                                                              n += (n < m) ? t : -t; //increment/decrement "n" by "t" (-0, -1, +2, -3, +4, -5,...)
                                                                                                                                              t++;
                                                                                                                                              r = 0;
                                                                                                                                              for (int i = 1; i <= n; i++) //foreach number between "1" and "n" increment "r" if the remainder of its division with "n" is 0 (thus being a factor)
                                                                                                                                              if (n % i == 0) r++;
                                                                                                                                              }
                                                                                                                                              return n;
                                                                                                                                              }

                                                                                                                                              Console.WriteLine(f(80)); //79





                                                                                                                                              share|improve this answer











                                                                                                                                              $endgroup$


















                                                                                                                                                2












                                                                                                                                                $begingroup$


                                                                                                                                                C# (Visual C# Interactive Compiler), 104 100 bytes



                                                                                                                                                n=>{int r=0,t=0,m=n;while(r!=2){n+=(n<m)?t:-t;t++;r=0;for(int i=1;i<=n;i++)if(n%i==0)r++;}return n;}


                                                                                                                                                Try it online!



                                                                                                                                                Explanation:



                                                                                                                                                int f(int n)
                                                                                                                                                {
                                                                                                                                                int r = 0; //stores the amount of factors of "n"
                                                                                                                                                int t = 0; //increment used to cover all the integers surrounding "n"
                                                                                                                                                int m = n; //placeholder to toggle between adding or substracting "t" to "n"

                                                                                                                                                while (r != 2) //while the amount of factors found for "n" is different to 2 ("1" + itself)
                                                                                                                                                {
                                                                                                                                                n += (n < m) ? t : -t; //increment/decrement "n" by "t" (-0, -1, +2, -3, +4, -5,...)
                                                                                                                                                t++;
                                                                                                                                                r = 0;
                                                                                                                                                for (int i = 1; i <= n; i++) //foreach number between "1" and "n" increment "r" if the remainder of its division with "n" is 0 (thus being a factor)
                                                                                                                                                if (n % i == 0) r++;
                                                                                                                                                }
                                                                                                                                                return n;
                                                                                                                                                }

                                                                                                                                                Console.WriteLine(f(80)); //79





                                                                                                                                                share|improve this answer











                                                                                                                                                $endgroup$
















                                                                                                                                                  2












                                                                                                                                                  2








                                                                                                                                                  2





                                                                                                                                                  $begingroup$


                                                                                                                                                  C# (Visual C# Interactive Compiler), 104 100 bytes



                                                                                                                                                  n=>{int r=0,t=0,m=n;while(r!=2){n+=(n<m)?t:-t;t++;r=0;for(int i=1;i<=n;i++)if(n%i==0)r++;}return n;}


                                                                                                                                                  Try it online!



                                                                                                                                                  Explanation:



                                                                                                                                                  int f(int n)
                                                                                                                                                  {
                                                                                                                                                  int r = 0; //stores the amount of factors of "n"
                                                                                                                                                  int t = 0; //increment used to cover all the integers surrounding "n"
                                                                                                                                                  int m = n; //placeholder to toggle between adding or substracting "t" to "n"

                                                                                                                                                  while (r != 2) //while the amount of factors found for "n" is different to 2 ("1" + itself)
                                                                                                                                                  {
                                                                                                                                                  n += (n < m) ? t : -t; //increment/decrement "n" by "t" (-0, -1, +2, -3, +4, -5,...)
                                                                                                                                                  t++;
                                                                                                                                                  r = 0;
                                                                                                                                                  for (int i = 1; i <= n; i++) //foreach number between "1" and "n" increment "r" if the remainder of its division with "n" is 0 (thus being a factor)
                                                                                                                                                  if (n % i == 0) r++;
                                                                                                                                                  }
                                                                                                                                                  return n;
                                                                                                                                                  }

                                                                                                                                                  Console.WriteLine(f(80)); //79





                                                                                                                                                  share|improve this answer











                                                                                                                                                  $endgroup$




                                                                                                                                                  C# (Visual C# Interactive Compiler), 104 100 bytes



                                                                                                                                                  n=>{int r=0,t=0,m=n;while(r!=2){n+=(n<m)?t:-t;t++;r=0;for(int i=1;i<=n;i++)if(n%i==0)r++;}return n;}


                                                                                                                                                  Try it online!



                                                                                                                                                  Explanation:



                                                                                                                                                  int f(int n)
                                                                                                                                                  {
                                                                                                                                                  int r = 0; //stores the amount of factors of "n"
                                                                                                                                                  int t = 0; //increment used to cover all the integers surrounding "n"
                                                                                                                                                  int m = n; //placeholder to toggle between adding or substracting "t" to "n"

                                                                                                                                                  while (r != 2) //while the amount of factors found for "n" is different to 2 ("1" + itself)
                                                                                                                                                  {
                                                                                                                                                  n += (n < m) ? t : -t; //increment/decrement "n" by "t" (-0, -1, +2, -3, +4, -5,...)
                                                                                                                                                  t++;
                                                                                                                                                  r = 0;
                                                                                                                                                  for (int i = 1; i <= n; i++) //foreach number between "1" and "n" increment "r" if the remainder of its division with "n" is 0 (thus being a factor)
                                                                                                                                                  if (n % i == 0) r++;
                                                                                                                                                  }
                                                                                                                                                  return n;
                                                                                                                                                  }

                                                                                                                                                  Console.WriteLine(f(80)); //79






                                                                                                                                                  share|improve this answer














                                                                                                                                                  share|improve this answer



                                                                                                                                                  share|improve this answer








                                                                                                                                                  edited Mar 29 at 8:50

























                                                                                                                                                  answered Mar 28 at 8:57









                                                                                                                                                  Innat3Innat3

                                                                                                                                                  1514




                                                                                                                                                  1514























                                                                                                                                                      2












                                                                                                                                                      $begingroup$

                                                                                                                                                      Java 8, 88 87 bytes





                                                                                                                                                      n->{for(int c=0,s=0,d,N=n;c!=2;s++)for(c=d=1,n+=n<N?s:-s;d<n;)if(n%++d<1)c++;return n;}


                                                                                                                                                      Port of @NaturalNumberGuy's (first) C answer, so make sure to upvote him!!

                                                                                                                                                      -1 byte thanks to @OlivierGrégoire.



                                                                                                                                                      Try it online.



                                                                                                                                                      Explanation:



                                                                                                                                                      n->{               // Method with integer as both parameter and return-type
                                                                                                                                                      for(int c=0, // Counter-integer, starting at 0
                                                                                                                                                      s=0, // Step-integer, starting at 0 as well
                                                                                                                                                      d, // Divisor-integer, uninitialized
                                                                                                                                                      N=n; // Copy of the input-integer
                                                                                                                                                      c!=2; // Loop as long as the counter is not exactly 2 yet:
                                                                                                                                                      s++) // After every iteration: increase the step-integer by 1
                                                                                                                                                      for(c=d=1, // (Re)set both the counter and divisor to 1
                                                                                                                                                      n+=n<N? // If the input is smaller than the input-copy:
                                                                                                                                                      s // Increase the input by the step-integer
                                                                                                                                                      : // Else:
                                                                                                                                                      -s; // Decrease the input by the step-integer
                                                                                                                                                      d<n;) // Inner loop as long as the divisor is smaller than the input
                                                                                                                                                      if(n%++d // Increase the divisor by 1 first with `++d`
                                                                                                                                                      <1) // And if the input is evenly divisible by the divisor:
                                                                                                                                                      c++; // Increase the counter-integer by 1
                                                                                                                                                      return n;} // Return the now modified input-integer as result





                                                                                                                                                      share|improve this answer











                                                                                                                                                      $endgroup$


















                                                                                                                                                        2












                                                                                                                                                        $begingroup$

                                                                                                                                                        Java 8, 88 87 bytes





                                                                                                                                                        n->{for(int c=0,s=0,d,N=n;c!=2;s++)for(c=d=1,n+=n<N?s:-s;d<n;)if(n%++d<1)c++;return n;}


                                                                                                                                                        Port of @NaturalNumberGuy's (first) C answer, so make sure to upvote him!!

                                                                                                                                                        -1 byte thanks to @OlivierGrégoire.



                                                                                                                                                        Try it online.



                                                                                                                                                        Explanation:



                                                                                                                                                        n->{               // Method with integer as both parameter and return-type
                                                                                                                                                        for(int c=0, // Counter-integer, starting at 0
                                                                                                                                                        s=0, // Step-integer, starting at 0 as well
                                                                                                                                                        d, // Divisor-integer, uninitialized
                                                                                                                                                        N=n; // Copy of the input-integer
                                                                                                                                                        c!=2; // Loop as long as the counter is not exactly 2 yet:
                                                                                                                                                        s++) // After every iteration: increase the step-integer by 1
                                                                                                                                                        for(c=d=1, // (Re)set both the counter and divisor to 1
                                                                                                                                                        n+=n<N? // If the input is smaller than the input-copy:
                                                                                                                                                        s // Increase the input by the step-integer
                                                                                                                                                        : // Else:
                                                                                                                                                        -s; // Decrease the input by the step-integer
                                                                                                                                                        d<n;) // Inner loop as long as the divisor is smaller than the input
                                                                                                                                                        if(n%++d // Increase the divisor by 1 first with `++d`
                                                                                                                                                        <1) // And if the input is evenly divisible by the divisor:
                                                                                                                                                        c++; // Increase the counter-integer by 1
                                                                                                                                                        return n;} // Return the now modified input-integer as result





                                                                                                                                                        share|improve this answer











                                                                                                                                                        $endgroup$
















                                                                                                                                                          2












                                                                                                                                                          2








                                                                                                                                                          2





                                                                                                                                                          $begingroup$

                                                                                                                                                          Java 8, 88 87 bytes





                                                                                                                                                          n->{for(int c=0,s=0,d,N=n;c!=2;s++)for(c=d=1,n+=n<N?s:-s;d<n;)if(n%++d<1)c++;return n;}


                                                                                                                                                          Port of @NaturalNumberGuy's (first) C answer, so make sure to upvote him!!

                                                                                                                                                          -1 byte thanks to @OlivierGrégoire.



                                                                                                                                                          Try it online.



                                                                                                                                                          Explanation:



                                                                                                                                                          n->{               // Method with integer as both parameter and return-type
                                                                                                                                                          for(int c=0, // Counter-integer, starting at 0
                                                                                                                                                          s=0, // Step-integer, starting at 0 as well
                                                                                                                                                          d, // Divisor-integer, uninitialized
                                                                                                                                                          N=n; // Copy of the input-integer
                                                                                                                                                          c!=2; // Loop as long as the counter is not exactly 2 yet:
                                                                                                                                                          s++) // After every iteration: increase the step-integer by 1
                                                                                                                                                          for(c=d=1, // (Re)set both the counter and divisor to 1
                                                                                                                                                          n+=n<N? // If the input is smaller than the input-copy:
                                                                                                                                                          s // Increase the input by the step-integer
                                                                                                                                                          : // Else:
                                                                                                                                                          -s; // Decrease the input by the step-integer
                                                                                                                                                          d<n;) // Inner loop as long as the divisor is smaller than the input
                                                                                                                                                          if(n%++d // Increase the divisor by 1 first with `++d`
                                                                                                                                                          <1) // And if the input is evenly divisible by the divisor:
                                                                                                                                                          c++; // Increase the counter-integer by 1
                                                                                                                                                          return n;} // Return the now modified input-integer as result





                                                                                                                                                          share|improve this answer











                                                                                                                                                          $endgroup$



                                                                                                                                                          Java 8, 88 87 bytes





                                                                                                                                                          n->{for(int c=0,s=0,d,N=n;c!=2;s++)for(c=d=1,n+=n<N?s:-s;d<n;)if(n%++d<1)c++;return n;}


                                                                                                                                                          Port of @NaturalNumberGuy's (first) C answer, so make sure to upvote him!!

                                                                                                                                                          -1 byte thanks to @OlivierGrégoire.



                                                                                                                                                          Try it online.



                                                                                                                                                          Explanation:



                                                                                                                                                          n->{               // Method with integer as both parameter and return-type
                                                                                                                                                          for(int c=0, // Counter-integer, starting at 0
                                                                                                                                                          s=0, // Step-integer, starting at 0 as well
                                                                                                                                                          d, // Divisor-integer, uninitialized
                                                                                                                                                          N=n; // Copy of the input-integer
                                                                                                                                                          c!=2; // Loop as long as the counter is not exactly 2 yet:
                                                                                                                                                          s++) // After every iteration: increase the step-integer by 1
                                                                                                                                                          for(c=d=1, // (Re)set both the counter and divisor to 1
                                                                                                                                                          n+=n<N? // If the input is smaller than the input-copy:
                                                                                                                                                          s // Increase the input by the step-integer
                                                                                                                                                          : // Else:
                                                                                                                                                          -s; // Decrease the input by the step-integer
                                                                                                                                                          d<n;) // Inner loop as long as the divisor is smaller than the input
                                                                                                                                                          if(n%++d // Increase the divisor by 1 first with `++d`
                                                                                                                                                          <1) // And if the input is evenly divisible by the divisor:
                                                                                                                                                          c++; // Increase the counter-integer by 1
                                                                                                                                                          return n;} // Return the now modified input-integer as result






                                                                                                                                                          share|improve this answer














                                                                                                                                                          share|improve this answer



                                                                                                                                                          share|improve this answer








                                                                                                                                                          edited Mar 29 at 13:06

























                                                                                                                                                          answered Mar 29 at 12:30









                                                                                                                                                          Kevin CruijssenKevin Cruijssen

                                                                                                                                                          42.4k570217




                                                                                                                                                          42.4k570217























                                                                                                                                                              2












                                                                                                                                                              $begingroup$


                                                                                                                                                              Java (JDK), 103 bytes





                                                                                                                                                              n->{int p=0,x=0,z=n,d;for(;p<1;p=p>0?z:0,z=z==n+x?n-++x:z+1)for(p=z/2,d=1;++d<z;)p=z%d<1?0:p;return p;}


                                                                                                                                                              Try it online!






                                                                                                                                                              share|improve this answer











                                                                                                                                                              $endgroup$













                                                                                                                                                              • $begingroup$
                                                                                                                                                                Umm.. I had already create a port of his answer.. ;) Although yours is 1 byte shorter, so something is different. EDIT: Ah, I have a result-integer outside the loop, and you modify the input inside the loop, hence the -1 byte for ;. :) Do you want me to delete my answer?.. Feel free to copy the explanation.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Kevin Cruijssen
                                                                                                                                                                Mar 29 at 12:50












                                                                                                                                                              • $begingroup$
                                                                                                                                                                @KevinCruijssen Oops, rollbacked!
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Olivier Grégoire
                                                                                                                                                                Mar 29 at 12:59










                                                                                                                                                              • $begingroup$
                                                                                                                                                                Sorry about that (and thanks for the -1 byte). I like your version as well, though. Already upvoted before I saw NaturalNumberGuy's answer.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Kevin Cruijssen
                                                                                                                                                                Mar 29 at 12:59
















                                                                                                                                                              2












                                                                                                                                                              $begingroup$


                                                                                                                                                              Java (JDK), 103 bytes





                                                                                                                                                              n->{int p=0,x=0,z=n,d;for(;p<1;p=p>0?z:0,z=z==n+x?n-++x:z+1)for(p=z/2,d=1;++d<z;)p=z%d<1?0:p;return p;}


                                                                                                                                                              Try it online!






                                                                                                                                                              share|improve this answer











                                                                                                                                                              $endgroup$













                                                                                                                                                              • $begingroup$
                                                                                                                                                                Umm.. I had already create a port of his answer.. ;) Although yours is 1 byte shorter, so something is different. EDIT: Ah, I have a result-integer outside the loop, and you modify the input inside the loop, hence the -1 byte for ;. :) Do you want me to delete my answer?.. Feel free to copy the explanation.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Kevin Cruijssen
                                                                                                                                                                Mar 29 at 12:50












                                                                                                                                                              • $begingroup$
                                                                                                                                                                @KevinCruijssen Oops, rollbacked!
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Olivier Grégoire
                                                                                                                                                                Mar 29 at 12:59










                                                                                                                                                              • $begingroup$
                                                                                                                                                                Sorry about that (and thanks for the -1 byte). I like your version as well, though. Already upvoted before I saw NaturalNumberGuy's answer.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Kevin Cruijssen
                                                                                                                                                                Mar 29 at 12:59














                                                                                                                                                              2












                                                                                                                                                              2








                                                                                                                                                              2





                                                                                                                                                              $begingroup$


                                                                                                                                                              Java (JDK), 103 bytes





                                                                                                                                                              n->{int p=0,x=0,z=n,d;for(;p<1;p=p>0?z:0,z=z==n+x?n-++x:z+1)for(p=z/2,d=1;++d<z;)p=z%d<1?0:p;return p;}


                                                                                                                                                              Try it online!






                                                                                                                                                              share|improve this answer











                                                                                                                                                              $endgroup$




                                                                                                                                                              Java (JDK), 103 bytes





                                                                                                                                                              n->{int p=0,x=0,z=n,d;for(;p<1;p=p>0?z:0,z=z==n+x?n-++x:z+1)for(p=z/2,d=1;++d<z;)p=z%d<1?0:p;return p;}


                                                                                                                                                              Try it online!







                                                                                                                                                              share|improve this answer














                                                                                                                                                              share|improve this answer



                                                                                                                                                              share|improve this answer








                                                                                                                                                              edited Mar 29 at 13:06

























                                                                                                                                                              answered Mar 29 at 11:23









                                                                                                                                                              Olivier GrégoireOlivier Grégoire

                                                                                                                                                              9,39511944




                                                                                                                                                              9,39511944












                                                                                                                                                              • $begingroup$
                                                                                                                                                                Umm.. I had already create a port of his answer.. ;) Although yours is 1 byte shorter, so something is different. EDIT: Ah, I have a result-integer outside the loop, and you modify the input inside the loop, hence the -1 byte for ;. :) Do you want me to delete my answer?.. Feel free to copy the explanation.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Kevin Cruijssen
                                                                                                                                                                Mar 29 at 12:50












                                                                                                                                                              • $begingroup$
                                                                                                                                                                @KevinCruijssen Oops, rollbacked!
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Olivier Grégoire
                                                                                                                                                                Mar 29 at 12:59










                                                                                                                                                              • $begingroup$
                                                                                                                                                                Sorry about that (and thanks for the -1 byte). I like your version as well, though. Already upvoted before I saw NaturalNumberGuy's answer.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Kevin Cruijssen
                                                                                                                                                                Mar 29 at 12:59


















                                                                                                                                                              • $begingroup$
                                                                                                                                                                Umm.. I had already create a port of his answer.. ;) Although yours is 1 byte shorter, so something is different. EDIT: Ah, I have a result-integer outside the loop, and you modify the input inside the loop, hence the -1 byte for ;. :) Do you want me to delete my answer?.. Feel free to copy the explanation.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Kevin Cruijssen
                                                                                                                                                                Mar 29 at 12:50












                                                                                                                                                              • $begingroup$
                                                                                                                                                                @KevinCruijssen Oops, rollbacked!
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Olivier Grégoire
                                                                                                                                                                Mar 29 at 12:59










                                                                                                                                                              • $begingroup$
                                                                                                                                                                Sorry about that (and thanks for the -1 byte). I like your version as well, though. Already upvoted before I saw NaturalNumberGuy's answer.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Kevin Cruijssen
                                                                                                                                                                Mar 29 at 12:59
















                                                                                                                                                              $begingroup$
                                                                                                                                                              Umm.. I had already create a port of his answer.. ;) Although yours is 1 byte shorter, so something is different. EDIT: Ah, I have a result-integer outside the loop, and you modify the input inside the loop, hence the -1 byte for ;. :) Do you want me to delete my answer?.. Feel free to copy the explanation.
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Kevin Cruijssen
                                                                                                                                                              Mar 29 at 12:50






                                                                                                                                                              $begingroup$
                                                                                                                                                              Umm.. I had already create a port of his answer.. ;) Although yours is 1 byte shorter, so something is different. EDIT: Ah, I have a result-integer outside the loop, and you modify the input inside the loop, hence the -1 byte for ;. :) Do you want me to delete my answer?.. Feel free to copy the explanation.
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Kevin Cruijssen
                                                                                                                                                              Mar 29 at 12:50














                                                                                                                                                              $begingroup$
                                                                                                                                                              @KevinCruijssen Oops, rollbacked!
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Olivier Grégoire
                                                                                                                                                              Mar 29 at 12:59




                                                                                                                                                              $begingroup$
                                                                                                                                                              @KevinCruijssen Oops, rollbacked!
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Olivier Grégoire
                                                                                                                                                              Mar 29 at 12:59












                                                                                                                                                              $begingroup$
                                                                                                                                                              Sorry about that (and thanks for the -1 byte). I like your version as well, though. Already upvoted before I saw NaturalNumberGuy's answer.
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Kevin Cruijssen
                                                                                                                                                              Mar 29 at 12:59




                                                                                                                                                              $begingroup$
                                                                                                                                                              Sorry about that (and thanks for the -1 byte). I like your version as well, though. Already upvoted before I saw NaturalNumberGuy's answer.
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Kevin Cruijssen
                                                                                                                                                              Mar 29 at 12:59











                                                                                                                                                              2












                                                                                                                                                              $begingroup$


                                                                                                                                                              Haskell, 79 74 bytes (thanks to Laikoni)



                                                                                                                                                              72 bytes as annonymus function (the initial "f=" could be removed in this case).





                                                                                                                                                              f=(!)(-1);n!x|x>1,all((>0).mod x)[2..x-1]=x|y<-x+n=last(-n+1:[-n-1|n>0])!y


                                                                                                                                                              Try it online!





                                                                                                                                                              original code:





                                                                                                                                                              f=(!)(-1);n!x|x>1&&all((>0).mod x)[2..x-1]=x|1>0=(last$(-n+1):[-n-1|n>0])!(x+n)


                                                                                                                                                              Try it online!



                                                                                                                                                              Explanation:





                                                                                                                                                              f x = (-1)!x

                                                                                                                                                              isPrime x = x > 1 && all (k -> x `mod` k /= 0)[2..x-1]
                                                                                                                                                              n!x | isPrime x = x -- return the first prime found
                                                                                                                                                              | n>0 = (-n-1)!(x+n) -- x is no prime, continue with x+n where n takes the
                                                                                                                                                              | otherwise = (-n+1)!(x+n) -- values -1,2,-3,4 .. in subsequent calls of (!)





                                                                                                                                                              share|improve this answer











                                                                                                                                                              $endgroup$









                                                                                                                                                              • 1




                                                                                                                                                                $begingroup$
                                                                                                                                                                Inside a guard you can use , instead of &&. (last$ ...) can be last(...), and the second guard 1>0 can be used for a binding to save parenthesis, e.g. y<-x+n.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Laikoni
                                                                                                                                                                Mar 30 at 10:57










                                                                                                                                                              • $begingroup$
                                                                                                                                                                Anonymous functions are generally allowed, so the initial f= does not need to be counted. Also the parenthesis enclosing (-1+n) can be dropped.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Laikoni
                                                                                                                                                                Mar 30 at 11:22










                                                                                                                                                              • $begingroup$
                                                                                                                                                                Thanks for the suggestions. I didn't know "," and bindings are allowed in function guards! But i don't really like the idea of an annonymous function as an answer. It doesn't feel right in my opinion.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Sachera
                                                                                                                                                                Mar 31 at 2:58












                                                                                                                                                              • $begingroup$
                                                                                                                                                                You can find more tips in our collection of tips for golfing in Haskell. There is also a Guide to Golfing Rules in Haskell and dedicated chat room: Of Monads and Men.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Laikoni
                                                                                                                                                                Mar 31 at 22:13
















                                                                                                                                                              2












                                                                                                                                                              $begingroup$


                                                                                                                                                              Haskell, 79 74 bytes (thanks to Laikoni)



                                                                                                                                                              72 bytes as annonymus function (the initial "f=" could be removed in this case).





                                                                                                                                                              f=(!)(-1);n!x|x>1,all((>0).mod x)[2..x-1]=x|y<-x+n=last(-n+1:[-n-1|n>0])!y


                                                                                                                                                              Try it online!





                                                                                                                                                              original code:





                                                                                                                                                              f=(!)(-1);n!x|x>1&&all((>0).mod x)[2..x-1]=x|1>0=(last$(-n+1):[-n-1|n>0])!(x+n)


                                                                                                                                                              Try it online!



                                                                                                                                                              Explanation:





                                                                                                                                                              f x = (-1)!x

                                                                                                                                                              isPrime x = x > 1 && all (k -> x `mod` k /= 0)[2..x-1]
                                                                                                                                                              n!x | isPrime x = x -- return the first prime found
                                                                                                                                                              | n>0 = (-n-1)!(x+n) -- x is no prime, continue with x+n where n takes the
                                                                                                                                                              | otherwise = (-n+1)!(x+n) -- values -1,2,-3,4 .. in subsequent calls of (!)





                                                                                                                                                              share|improve this answer











                                                                                                                                                              $endgroup$









                                                                                                                                                              • 1




                                                                                                                                                                $begingroup$
                                                                                                                                                                Inside a guard you can use , instead of &&. (last$ ...) can be last(...), and the second guard 1>0 can be used for a binding to save parenthesis, e.g. y<-x+n.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Laikoni
                                                                                                                                                                Mar 30 at 10:57










                                                                                                                                                              • $begingroup$
                                                                                                                                                                Anonymous functions are generally allowed, so the initial f= does not need to be counted. Also the parenthesis enclosing (-1+n) can be dropped.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Laikoni
                                                                                                                                                                Mar 30 at 11:22










                                                                                                                                                              • $begingroup$
                                                                                                                                                                Thanks for the suggestions. I didn't know "," and bindings are allowed in function guards! But i don't really like the idea of an annonymous function as an answer. It doesn't feel right in my opinion.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Sachera
                                                                                                                                                                Mar 31 at 2:58












                                                                                                                                                              • $begingroup$
                                                                                                                                                                You can find more tips in our collection of tips for golfing in Haskell. There is also a Guide to Golfing Rules in Haskell and dedicated chat room: Of Monads and Men.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Laikoni
                                                                                                                                                                Mar 31 at 22:13














                                                                                                                                                              2












                                                                                                                                                              2








                                                                                                                                                              2





                                                                                                                                                              $begingroup$


                                                                                                                                                              Haskell, 79 74 bytes (thanks to Laikoni)



                                                                                                                                                              72 bytes as annonymus function (the initial "f=" could be removed in this case).





                                                                                                                                                              f=(!)(-1);n!x|x>1,all((>0).mod x)[2..x-1]=x|y<-x+n=last(-n+1:[-n-1|n>0])!y


                                                                                                                                                              Try it online!





                                                                                                                                                              original code:





                                                                                                                                                              f=(!)(-1);n!x|x>1&&all((>0).mod x)[2..x-1]=x|1>0=(last$(-n+1):[-n-1|n>0])!(x+n)


                                                                                                                                                              Try it online!



                                                                                                                                                              Explanation:





                                                                                                                                                              f x = (-1)!x

                                                                                                                                                              isPrime x = x > 1 && all (k -> x `mod` k /= 0)[2..x-1]
                                                                                                                                                              n!x | isPrime x = x -- return the first prime found
                                                                                                                                                              | n>0 = (-n-1)!(x+n) -- x is no prime, continue with x+n where n takes the
                                                                                                                                                              | otherwise = (-n+1)!(x+n) -- values -1,2,-3,4 .. in subsequent calls of (!)





                                                                                                                                                              share|improve this answer











                                                                                                                                                              $endgroup$




                                                                                                                                                              Haskell, 79 74 bytes (thanks to Laikoni)



                                                                                                                                                              72 bytes as annonymus function (the initial "f=" could be removed in this case).





                                                                                                                                                              f=(!)(-1);n!x|x>1,all((>0).mod x)[2..x-1]=x|y<-x+n=last(-n+1:[-n-1|n>0])!y


                                                                                                                                                              Try it online!





                                                                                                                                                              original code:





                                                                                                                                                              f=(!)(-1);n!x|x>1&&all((>0).mod x)[2..x-1]=x|1>0=(last$(-n+1):[-n-1|n>0])!(x+n)


                                                                                                                                                              Try it online!



                                                                                                                                                              Explanation:





                                                                                                                                                              f x = (-1)!x

                                                                                                                                                              isPrime x = x > 1 && all (k -> x `mod` k /= 0)[2..x-1]
                                                                                                                                                              n!x | isPrime x = x -- return the first prime found
                                                                                                                                                              | n>0 = (-n-1)!(x+n) -- x is no prime, continue with x+n where n takes the
                                                                                                                                                              | otherwise = (-n+1)!(x+n) -- values -1,2,-3,4 .. in subsequent calls of (!)






                                                                                                                                                              share|improve this answer














                                                                                                                                                              share|improve this answer



                                                                                                                                                              share|improve this answer








                                                                                                                                                              edited Mar 31 at 2:56

























                                                                                                                                                              answered Mar 29 at 2:38









                                                                                                                                                              SacheraSachera

                                                                                                                                                              512




                                                                                                                                                              512








                                                                                                                                                              • 1




                                                                                                                                                                $begingroup$
                                                                                                                                                                Inside a guard you can use , instead of &&. (last$ ...) can be last(...), and the second guard 1>0 can be used for a binding to save parenthesis, e.g. y<-x+n.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Laikoni
                                                                                                                                                                Mar 30 at 10:57










                                                                                                                                                              • $begingroup$
                                                                                                                                                                Anonymous functions are generally allowed, so the initial f= does not need to be counted. Also the parenthesis enclosing (-1+n) can be dropped.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Laikoni
                                                                                                                                                                Mar 30 at 11:22










                                                                                                                                                              • $begingroup$
                                                                                                                                                                Thanks for the suggestions. I didn't know "," and bindings are allowed in function guards! But i don't really like the idea of an annonymous function as an answer. It doesn't feel right in my opinion.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Sachera
                                                                                                                                                                Mar 31 at 2:58












                                                                                                                                                              • $begingroup$
                                                                                                                                                                You can find more tips in our collection of tips for golfing in Haskell. There is also a Guide to Golfing Rules in Haskell and dedicated chat room: Of Monads and Men.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Laikoni
                                                                                                                                                                Mar 31 at 22:13














                                                                                                                                                              • 1




                                                                                                                                                                $begingroup$
                                                                                                                                                                Inside a guard you can use , instead of &&. (last$ ...) can be last(...), and the second guard 1>0 can be used for a binding to save parenthesis, e.g. y<-x+n.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Laikoni
                                                                                                                                                                Mar 30 at 10:57










                                                                                                                                                              • $begingroup$
                                                                                                                                                                Anonymous functions are generally allowed, so the initial f= does not need to be counted. Also the parenthesis enclosing (-1+n) can be dropped.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Laikoni
                                                                                                                                                                Mar 30 at 11:22










                                                                                                                                                              • $begingroup$
                                                                                                                                                                Thanks for the suggestions. I didn't know "," and bindings are allowed in function guards! But i don't really like the idea of an annonymous function as an answer. It doesn't feel right in my opinion.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Sachera
                                                                                                                                                                Mar 31 at 2:58












                                                                                                                                                              • $begingroup$
                                                                                                                                                                You can find more tips in our collection of tips for golfing in Haskell. There is also a Guide to Golfing Rules in Haskell and dedicated chat room: Of Monads and Men.
                                                                                                                                                                $endgroup$
                                                                                                                                                                – Laikoni
                                                                                                                                                                Mar 31 at 22:13








                                                                                                                                                              1




                                                                                                                                                              1




                                                                                                                                                              $begingroup$
                                                                                                                                                              Inside a guard you can use , instead of &&. (last$ ...) can be last(...), and the second guard 1>0 can be used for a binding to save parenthesis, e.g. y<-x+n.
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Laikoni
                                                                                                                                                              Mar 30 at 10:57




                                                                                                                                                              $begingroup$
                                                                                                                                                              Inside a guard you can use , instead of &&. (last$ ...) can be last(...), and the second guard 1>0 can be used for a binding to save parenthesis, e.g. y<-x+n.
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Laikoni
                                                                                                                                                              Mar 30 at 10:57












                                                                                                                                                              $begingroup$
                                                                                                                                                              Anonymous functions are generally allowed, so the initial f= does not need to be counted. Also the parenthesis enclosing (-1+n) can be dropped.
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Laikoni
                                                                                                                                                              Mar 30 at 11:22




                                                                                                                                                              $begingroup$
                                                                                                                                                              Anonymous functions are generally allowed, so the initial f= does not need to be counted. Also the parenthesis enclosing (-1+n) can be dropped.
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Laikoni
                                                                                                                                                              Mar 30 at 11:22












                                                                                                                                                              $begingroup$
                                                                                                                                                              Thanks for the suggestions. I didn't know "," and bindings are allowed in function guards! But i don't really like the idea of an annonymous function as an answer. It doesn't feel right in my opinion.
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Sachera
                                                                                                                                                              Mar 31 at 2:58






                                                                                                                                                              $begingroup$
                                                                                                                                                              Thanks for the suggestions. I didn't know "," and bindings are allowed in function guards! But i don't really like the idea of an annonymous function as an answer. It doesn't feel right in my opinion.
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Sachera
                                                                                                                                                              Mar 31 at 2:58














                                                                                                                                                              $begingroup$
                                                                                                                                                              You can find more tips in our collection of tips for golfing in Haskell. There is also a Guide to Golfing Rules in Haskell and dedicated chat room: Of Monads and Men.
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Laikoni
                                                                                                                                                              Mar 31 at 22:13




                                                                                                                                                              $begingroup$
                                                                                                                                                              You can find more tips in our collection of tips for golfing in Haskell. There is also a Guide to Golfing Rules in Haskell and dedicated chat room: Of Monads and Men.
                                                                                                                                                              $endgroup$
                                                                                                                                                              – Laikoni
                                                                                                                                                              Mar 31 at 22:13











                                                                                                                                                              2












                                                                                                                                                              $begingroup$


                                                                                                                                                              VDM-SL, 161 bytes





                                                                                                                                                              f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})


                                                                                                                                                              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:



                                                                                                                                                              functions
                                                                                                                                                              f:nat1+>nat1
                                                                                                                                                              f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})


                                                                                                                                                              Explanation:



                                                                                                                                                              f(i)==                                        /* f is a function which takes a nat1 (natural number not including 0)*/
                                                                                                                                                              (lambda p:set of nat1 /* define a lambda which takes a set of nat1*/
                                                                                                                                                              &let z in set p be st /* which has an element z in the set such that */
                                                                                                                                                              forall m in set p /* for every element in the set*/
                                                                                                                                                              &abs(m-i) /* the difference between the element m and the input*/
                                                                                                                                                              >=abs(z-i) /* is greater than or equal to the difference between the element z and the input */
                                                                                                                                                              in z) /* and return z from the lambda */
                                                                                                                                                              ( /* apply this lambda to... */
                                                                                                                                                              { /* a set defined by comprehension as.. */
                                                                                                                                                              x| /* all elements x such that.. */
                                                                                                                                                              x in set{1,...,9**7} /* x is between 1 and 9^7 */
                                                                                                                                                              &forall y in set{2,...,1003} /* and for all values between 2 and 1003*/
                                                                                                                                                              &y<>x=>x mod y<>0 /* y is not x implies x is not divisible by y*/
                                                                                                                                                              }
                                                                                                                                                              )





                                                                                                                                                              share|improve this answer











                                                                                                                                                              $endgroup$


















                                                                                                                                                                2












                                                                                                                                                                $begingroup$


                                                                                                                                                                VDM-SL, 161 bytes





                                                                                                                                                                f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})


                                                                                                                                                                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:



                                                                                                                                                                functions
                                                                                                                                                                f:nat1+>nat1
                                                                                                                                                                f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})


                                                                                                                                                                Explanation:



                                                                                                                                                                f(i)==                                        /* f is a function which takes a nat1 (natural number not including 0)*/
                                                                                                                                                                (lambda p:set of nat1 /* define a lambda which takes a set of nat1*/
                                                                                                                                                                &let z in set p be st /* which has an element z in the set such that */
                                                                                                                                                                forall m in set p /* for every element in the set*/
                                                                                                                                                                &abs(m-i) /* the difference between the element m and the input*/
                                                                                                                                                                >=abs(z-i) /* is greater than or equal to the difference between the element z and the input */
                                                                                                                                                                in z) /* and return z from the lambda */
                                                                                                                                                                ( /* apply this lambda to... */
                                                                                                                                                                { /* a set defined by comprehension as.. */
                                                                                                                                                                x| /* all elements x such that.. */
                                                                                                                                                                x in set{1,...,9**7} /* x is between 1 and 9^7 */
                                                                                                                                                                &forall y in set{2,...,1003} /* and for all values between 2 and 1003*/
                                                                                                                                                                &y<>x=>x mod y<>0 /* y is not x implies x is not divisible by y*/
                                                                                                                                                                }
                                                                                                                                                                )





                                                                                                                                                                share|improve this answer











                                                                                                                                                                $endgroup$
















                                                                                                                                                                  2












                                                                                                                                                                  2








                                                                                                                                                                  2





                                                                                                                                                                  $begingroup$


                                                                                                                                                                  VDM-SL, 161 bytes





                                                                                                                                                                  f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})


                                                                                                                                                                  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:



                                                                                                                                                                  functions
                                                                                                                                                                  f:nat1+>nat1
                                                                                                                                                                  f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})


                                                                                                                                                                  Explanation:



                                                                                                                                                                  f(i)==                                        /* f is a function which takes a nat1 (natural number not including 0)*/
                                                                                                                                                                  (lambda p:set of nat1 /* define a lambda which takes a set of nat1*/
                                                                                                                                                                  &let z in set p be st /* which has an element z in the set such that */
                                                                                                                                                                  forall m in set p /* for every element in the set*/
                                                                                                                                                                  &abs(m-i) /* the difference between the element m and the input*/
                                                                                                                                                                  >=abs(z-i) /* is greater than or equal to the difference between the element z and the input */
                                                                                                                                                                  in z) /* and return z from the lambda */
                                                                                                                                                                  ( /* apply this lambda to... */
                                                                                                                                                                  { /* a set defined by comprehension as.. */
                                                                                                                                                                  x| /* all elements x such that.. */
                                                                                                                                                                  x in set{1,...,9**7} /* x is between 1 and 9^7 */
                                                                                                                                                                  &forall y in set{2,...,1003} /* and for all values between 2 and 1003*/
                                                                                                                                                                  &y<>x=>x mod y<>0 /* y is not x implies x is not divisible by y*/
                                                                                                                                                                  }
                                                                                                                                                                  )





                                                                                                                                                                  share|improve this answer











                                                                                                                                                                  $endgroup$




                                                                                                                                                                  VDM-SL, 161 bytes





                                                                                                                                                                  f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})


                                                                                                                                                                  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:



                                                                                                                                                                  functions
                                                                                                                                                                  f:nat1+>nat1
                                                                                                                                                                  f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})


                                                                                                                                                                  Explanation:



                                                                                                                                                                  f(i)==                                        /* f is a function which takes a nat1 (natural number not including 0)*/
                                                                                                                                                                  (lambda p:set of nat1 /* define a lambda which takes a set of nat1*/
                                                                                                                                                                  &let z in set p be st /* which has an element z in the set such that */
                                                                                                                                                                  forall m in set p /* for every element in the set*/
                                                                                                                                                                  &abs(m-i) /* the difference between the element m and the input*/
                                                                                                                                                                  >=abs(z-i) /* is greater than or equal to the difference between the element z and the input */
                                                                                                                                                                  in z) /* and return z from the lambda */
                                                                                                                                                                  ( /* apply this lambda to... */
                                                                                                                                                                  { /* a set defined by comprehension as.. */
                                                                                                                                                                  x| /* all elements x such that.. */
                                                                                                                                                                  x in set{1,...,9**7} /* x is between 1 and 9^7 */
                                                                                                                                                                  &forall y in set{2,...,1003} /* and for all values between 2 and 1003*/
                                                                                                                                                                  &y<>x=>x mod y<>0 /* y is not x implies x is not divisible by y*/
                                                                                                                                                                  }
                                                                                                                                                                  )






                                                                                                                                                                  share|improve this answer














                                                                                                                                                                  share|improve this answer



                                                                                                                                                                  share|improve this answer








                                                                                                                                                                  edited Apr 1 at 15:52

























                                                                                                                                                                  answered Mar 27 at 16:31









                                                                                                                                                                  Expired DataExpired Data

                                                                                                                                                                  56314




                                                                                                                                                                  56314























                                                                                                                                                                      1












                                                                                                                                                                      $begingroup$


                                                                                                                                                                      C# (Visual C# Interactive Compiler), 112 bytes





                                                                                                                                                                      g=>Enumerable.Range(2,2<<20).Where(x=>Enumerable.Range(1,x).Count(y=>x%y<1)<3).OrderBy(x=>Math.Abs(x-g)).First()


                                                                                                                                                                      Try it online!



                                                                                                                                                                      Left shifts by 20 in submission but 10 in TIO so that TIO terminates for test cases.






                                                                                                                                                                      share|improve this answer









                                                                                                                                                                      $endgroup$


















                                                                                                                                                                        1












                                                                                                                                                                        $begingroup$


                                                                                                                                                                        C# (Visual C# Interactive Compiler), 112 bytes





                                                                                                                                                                        g=>Enumerable.Range(2,2<<20).Where(x=>Enumerable.Range(1,x).Count(y=>x%y<1)<3).OrderBy(x=>Math.Abs(x-g)).First()


                                                                                                                                                                        Try it online!



                                                                                                                                                                        Left shifts by 20 in submission but 10 in TIO so that TIO terminates for test cases.






                                                                                                                                                                        share|improve this answer









                                                                                                                                                                        $endgroup$
















                                                                                                                                                                          1












                                                                                                                                                                          1








                                                                                                                                                                          1





                                                                                                                                                                          $begingroup$


                                                                                                                                                                          C# (Visual C# Interactive Compiler), 112 bytes





                                                                                                                                                                          g=>Enumerable.Range(2,2<<20).Where(x=>Enumerable.Range(1,x).Count(y=>x%y<1)<3).OrderBy(x=>Math.Abs(x-g)).First()


                                                                                                                                                                          Try it online!



                                                                                                                                                                          Left shifts by 20 in submission but 10 in TIO so that TIO terminates for test cases.






                                                                                                                                                                          share|improve this answer









                                                                                                                                                                          $endgroup$




                                                                                                                                                                          C# (Visual C# Interactive Compiler), 112 bytes





                                                                                                                                                                          g=>Enumerable.Range(2,2<<20).Where(x=>Enumerable.Range(1,x).Count(y=>x%y<1)<3).OrderBy(x=>Math.Abs(x-g)).First()


                                                                                                                                                                          Try it online!



                                                                                                                                                                          Left shifts by 20 in submission but 10 in TIO so that TIO terminates for test cases.







                                                                                                                                                                          share|improve this answer












                                                                                                                                                                          share|improve this answer



                                                                                                                                                                          share|improve this answer










                                                                                                                                                                          answered Mar 27 at 16:43









                                                                                                                                                                          Expired DataExpired Data

                                                                                                                                                                          56314




                                                                                                                                                                          56314























                                                                                                                                                                              1












                                                                                                                                                                              $begingroup$

                                                                                                                                                                              Swift, 186 bytes



                                                                                                                                                                              func p(a:Int){let b=q(a:a,b:-1),c=q(a:a,b:1);print(a-b<=c-a ? b:c)}
                                                                                                                                                                              func q(a:Int,b:Int)->Int{var k=max(a,2),c=2;while k>c && c != a/2{if k%c==0{k+=b;c=2}else{c=c==2 ? c+1:c+2}};return k}


                                                                                                                                                                              Try it online!






                                                                                                                                                                              share|improve this answer









                                                                                                                                                                              $endgroup$


















                                                                                                                                                                                1












                                                                                                                                                                                $begingroup$

                                                                                                                                                                                Swift, 186 bytes



                                                                                                                                                                                func p(a:Int){let b=q(a:a,b:-1),c=q(a:a,b:1);print(a-b<=c-a ? b:c)}
                                                                                                                                                                                func q(a:Int,b:Int)->Int{var k=max(a,2),c=2;while k>c && c != a/2{if k%c==0{k+=b;c=2}else{c=c==2 ? c+1:c+2}};return k}


                                                                                                                                                                                Try it online!






                                                                                                                                                                                share|improve this answer









                                                                                                                                                                                $endgroup$
















                                                                                                                                                                                  1












                                                                                                                                                                                  1








                                                                                                                                                                                  1





                                                                                                                                                                                  $begingroup$

                                                                                                                                                                                  Swift, 186 bytes



                                                                                                                                                                                  func p(a:Int){let b=q(a:a,b:-1),c=q(a:a,b:1);print(a-b<=c-a ? b:c)}
                                                                                                                                                                                  func q(a:Int,b:Int)->Int{var k=max(a,2),c=2;while k>c && c != a/2{if k%c==0{k+=b;c=2}else{c=c==2 ? c+1:c+2}};return k}


                                                                                                                                                                                  Try it online!






                                                                                                                                                                                  share|improve this answer









                                                                                                                                                                                  $endgroup$



                                                                                                                                                                                  Swift, 186 bytes



                                                                                                                                                                                  func p(a:Int){let b=q(a:a,b:-1),c=q(a:a,b:1);print(a-b<=c-a ? b:c)}
                                                                                                                                                                                  func q(a:Int,b:Int)->Int{var k=max(a,2),c=2;while k>c && c != a/2{if k%c==0{k+=b;c=2}else{c=c==2 ? c+1:c+2}};return k}


                                                                                                                                                                                  Try it online!







                                                                                                                                                                                  share|improve this answer












                                                                                                                                                                                  share|improve this answer



                                                                                                                                                                                  share|improve this answer










                                                                                                                                                                                  answered Mar 27 at 18:24









                                                                                                                                                                                  onnowebonnoweb

                                                                                                                                                                                  1613




                                                                                                                                                                                  1613






















                                                                                                                                                                                      1 2
                                                                                                                                                                                      next

















                                                                                                                                                                                      draft saved

                                                                                                                                                                                      draft discarded




















































                                                                                                                                                                                      If this is an answer to a challenge…




                                                                                                                                                                                      • …Be sure to follow the challenge specification. However, please refrain from exploiting obvious loopholes. Answers abusing any of the standard loopholes are considered invalid. If you think a specification is unclear or underspecified, comment on the question instead.


                                                                                                                                                                                      • …Try to optimize your score. For instance, answers to code-golf challenges should attempt to be as short as possible. You can always include a readable version of the code in addition to the competitive one.
                                                                                                                                                                                        Explanations of your answer make it more interesting to read and are very much encouraged.


                                                                                                                                                                                      • …Include a short header which indicates the language(s) of your code and its score, as defined by the challenge.



                                                                                                                                                                                      More generally…




                                                                                                                                                                                      • …Please make sure to answer the question and provide sufficient detail.


                                                                                                                                                                                      • …Avoid asking for help, clarification or responding to other answers (use comments instead).





                                                                                                                                                                                      draft saved


                                                                                                                                                                                      draft discarded














                                                                                                                                                                                      StackExchange.ready(
                                                                                                                                                                                      function () {
                                                                                                                                                                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f182305%2freturn-the-closest-prime-number%23new-answer', 'question_page');
                                                                                                                                                                                      }
                                                                                                                                                                                      );

                                                                                                                                                                                      Post as a guest















                                                                                                                                                                                      Required, but never shown





















































                                                                                                                                                                                      Required, but never shown














                                                                                                                                                                                      Required, but never shown












                                                                                                                                                                                      Required, but never shown







                                                                                                                                                                                      Required, but never shown

































                                                                                                                                                                                      Required, but never shown














                                                                                                                                                                                      Required, but never shown












                                                                                                                                                                                      Required, but never shown







                                                                                                                                                                                      Required, but never shown







                                                                                                                                                                                      Popular posts from this blog

                                                                                                                                                                                      "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                                                                                                                                                                                      Alcedinidae

                                                                                                                                                                                      RAC Tourist Trophy