[Question]
  [
# 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
```
  
[Answer]
# 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!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k4j3VYjXyfF1s82Tztf09bOT1VXN8U@HSSmaZWiawhi2hjY6@Zb1eVrWvlpJiT8T87PK87PSdXLyU/XSNOwMNDU5EIVMjTAFDPFELHEVGNshGmWpuZ/AA "JavaScript (Node.js) – 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)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
Åps.x
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cGtBsV7F//@GxsbmAA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##yy9OTMpM/V9TVmmvpKBrp6BkX1n5/3BrQbFexX@d/xYGXIYGBlymXJYA)
Inefficient for big numbers
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 3 bytes
```
ṅD⌡
```
[Try it online!](https://tio.run/##S0/MTPz//@HOVpdHPQv//zc1NgIA "Gaia – 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
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 40 bytes
```
@(n)p([~,k]=min(abs(n-(p=primes(2*n)))))
```
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI0@zQCO6Tic71jY3M08jMalYI09Xo8C2oCgzN7VYw0grTxME/qdpWBhocqVpGBqAKVMQYQlmGRuBxTX/AwA "Octave – Try It Online")
This uses the fact that there is always a prime between `n` and `2*n` ([Bertrand–Chebyshev theorem](https://en.wikipedia.org/wiki/Bertrand%27s_postulate)).
### 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
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 bytes
```
_j}cU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X2p9Y1U&input=NA) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=X2p9Y1U&input=WzgwLDEwMCw1LDksNTMyLDFd)
```
_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
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes
```
Nearest[Prime~Array~78499,#,1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y81sSi1uCQ6oCgzN7XOsagosbLO3MLE0lJHWccwVu0/UDyvxEErTd@h2sJAx9DAQMdUx1LH1NhIx7D2/38A "Wolfram Language (Mathematica) – 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).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 bytes
```
ḤÆRạÞµḢ
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//4bikw4ZS4bqhw57CteG4ov///zk5OQ "Jelly – Try It Online")
Slow for larger input, but works ok for the requested range. Thanks to @EriktheOutgolfer for saving 2 bytes!
[Answer]
# [Python 2](https://docs.python.org/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!](https://tio.run/##HctBDoMgEEbhdXuK2ZjAgEmhO1MOg1EsmfpLqBtPT0mXL/leuc73Ad9aCp@4z0skWAnOluAmeYGfEQvtGUoMxjIIe4ZNqiPTEQuLHnusV4jzVxu0dFQCZVCN2FblrH/o6X4rNeOk/6rbDw "Python 2 – Try It Online")
A recursive function that uses the [Wilson's Theorem](https://codegolf.stackexchange.com/a/27022/20260) 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.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
z-Ån
```
[Try it online!](https://tio.run/##yy9OTMpM/V9TVmmvpKBrp6BkX1n5v0r3cGvef53/FgZchgYGXKZcllymxkZchgA "05AB1E – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~7~~ 5 bytes
```
;I≜-ṗ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39rzUecc3Yc7p///b2hgYPA/CgA "Brachylog – 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
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~87~~ ~~76~~ ~~74~~ 72 bytes
Optimization of innat3's [C# (Visual C# Interactive Compiler), 100 bytes](https://codegolf.stackexchange.com/a/182364/83073)
```
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!](https://tio.run/##fc5BCoMwFATQdT1FEISE/EBUBG1Me5FuipDyF/mWkJ169tS4b1YDw2OYRX2WJSXHCRAiBPBic2vg0WrwlkxQnYlSitwFi7YFkpZm/4x3FQ3OZKiREvc9nMgcyb@RuKi26vYNSNHxuumRqQc740U1sFEDc3zUQpi/ptUXOqOkhmyGkpiymIobfXet9F3xz/UmiyP9AA "C (gcc) – Try It Online")
[Answer]
# Pyth, 10 bytes
```
haDQfP_TSy
```
Try it online [here](https://pyth.herokuapp.com/?code=haDQfP_TSy&input=1000&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=haDQfP_TSy&test_suite=1&test_suite_input=80%0A100%0A5%0A9&debug=0).
```
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
```
[Answer]
# [Factor](https://factorcode.org/), 91 bytes
```
: p ( x -- x ) [ nprimes ] keep dupd [ - abs ] curry map swap zip natural-sort first last ;
```
[Try it online!](https://tio.run/##LY07DsJADER7TjElFBvxERKEAyCaNIgKUSzBQETYLLYjCJcPTkLz7BnLM1efa8XtYb/Ltim8SJULHsSBSjy93nskkYsnCSKTamMiKIReNYXcXKlYi3DDZrTLUmTkmURd/9KmiBjjA@cMExwR/lEnK6GISx0v5jr4c@flNXNjlRHyNnyLiOC1Zl@6rgXXgkVResOmXU0tPBnNpsNc9lwP@2I@3Dq2Pw "Factor – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 35 bytes
```
{$_+=($*=-1)*$++until .is-prime;$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJKZV1BaomCrYGxqzQXkqyXl5CdnA/n/q1XitW01VLRsdQ01tVS0tUvzSjJzFPQyi3ULijJzU61V4mv/W3MVJ8L0aECM0vwPAA "Perl 6 – 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.
[Answer]
# 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!](https://tio.run/##TY5LboNADIb3cworEtJYDBIkSpTWkC56jDQLD4HIUjtFQFd0zk4NaaR44ef/2a6z@pPDbZ47y05war97K1VBaSolE0prOZGywL4Zf/oAOf0nfCoo1sr4O@MrJvJpuhCdzTLG3856fHBL/uZfmeJsJIzwxRIsmsmA2tIYm2F856EZzheoYIJj7qDI1e0dvKjfbbWGSGYl1i@VEtXmpKGEA4H@jOv4vnaxrldZazfJFbITJNePsHFPt@TioLbPNSKtcDRx/gM "C (clang) – Try It Online")
[Answer]
# [Tidy](https://github.com/ConorOBrien-Foxx/Tidy), 43 bytes
```
{x:(prime↦splice(]x,-1,-∞],[x,∞]))@0}
```
[Try it online!](https://tio.run/##K8lMqfyfpmBlq/C/usJKo6AoMzf1Uduy4oKczORUjdgKHV1DHd1HHfNidaIrdEC0pqaDQe3/kmSQlmQNCwMdBUMDIGGqo2AJJI2NgHxNrmqFCgUrhfKizJLUnDyNCh0FJQVdOwUlHYU0jQpNTYVahfw8hZLk/wA "Tidy – 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).
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~20~~ 15 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Tacit prefix function inspired by [Galen Ivanov's J answer](https://codegolf.stackexchange.com/a/182340/43319).
```
⊢(⊃⍋⍤|⍤-⊇⊢)¯2⍭⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXIo1HXc2Persf9S6pAWLdR13tQEHNQ@uNHvWufdS7@X/ao7YJj3r7HvVN9fQHKj203vhR20QgLzjIGUiGeHgG/09TsDDgSlMwNACRpkBsCaKNjYCkMQA "APL (Dyalog Extended) – 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)
[Answer]
# [Python 2 (Cython)](http://cython.org/), 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!](https://tio.run/##PYxBCoAwDAS/kosQRS8VL4KPiVq1GGOoPdjX1yLoaXeGZTWG7RTTTG@mxAPTMc4E2h9OcHEcrMffETNqIbCcHgScgCdZLZpay7L@e9Vm2m38vu6exgvvJo@SeicBGbvWZHoA "Python 2 (Cython) – Try It Online")
[Answer]
## [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~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!](https://tio.run/##ZYyxCsJAEER7vyIWwh2XwBkR1M3GzsreDwh3uGBW2GywCPn281JqioHh8Wa6oeoGSreRu4ZYy5w2YmJsp1wLQV9qTo8Mnye9gpEt1nZih4ab3l71Uimoc5BNiG8xy4pwD9TkCTlnKRreEaK3krVZgo7CBcOcYPMQ0nAnDiaak7f2l@z9Ch3/wXllHOrVzwLSFw)
**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
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes
```
If[PrimeQ[s=#],s,#&@@Nearest[s~NextPrime~{-1,1},s]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zMtOqAoMzc1MLrYVjlWp1hHWc3BwS81sSi1uCS6uM4vtaIELF9XrWuoY1irUxwbq/YfKJJXoqDvkK7vUG1hoGNoYKBjqmNZ@/8/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# 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 
```
[Answer]
# [J](http://jsoftware.com/), ~~19~~ 15 bytes
```
(0{]/:|@-)p:@i.
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F/DoDpW36rGQVezwMohU@@/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqChQGMZWgAZ5rCGJZwEWMjuLr/AA "J – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/create_explanation.py), 10 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
∞╒g¶áÅ-±├Þ
```
[Try it online.](https://tio.run/##ATEAzv9tYXRoZ29sZv//4oie4pWSZ8K2w6HDhS3CseKUnMOe//84MAoxMDAKNQo5CjUzMgox)
**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)
```
[Answer]
# 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](https://codegolf.stackexchange.com/a/182420/52210), **so make sure to upvote him!!**  
-1 byte thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##NU9BasMwELznFdtAwUKysVMCTWS1L6gvOYYcVEkuSpx1kOSUYnztA/rEfsSV3eSwAzs77Mwc5VWmR30aVSO9hzdpEfoFgMVgXC2VgWpaZwLqZEIkPDLDIoIPMlgFFSCIEdOXvm7drFEiZz6OZpVArh7EintKyXRWQouCIRVYVq9@m3quS@TE1gk@UqrLgihKuTOhcwjIh5FPTpfuvYlON8NrazWcY9ZkF5zFj/0BJPnPeU9gYQtoPqfc@0P/nLMiz9mabdj6acWKgcxigN2XD@actV3ILvFTaDCxdAm/3z@wpJjFxuRWdxj/AA)
**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
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 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!](https://tio.run/##VU89b8IwEN35FSekSEkd3ISKqo0xqGOHigExVR1cnCCniWPZlwiC@O2uQ6cO7z7f6d6rxSAWtfzxqjWdRahDT3tUDa16fUTVafrAZsdGOAcfQmm4zgBM/92oIzgUGNLQKQlt2MV7tEqfPr9A2JNL7lSAd40HLexlZ0orsLNQAQfwerG5Ko1geJaeA0auU8mqzsbMrHNmuNlk27GYFiPnmpy3ekHIuRhJnkwsw8fHZSp5zgiR65ElYRDJdb7NCsNsib3VYNjNs7uIewhnEA/CTvKKfxoB9heHZUu7HqkJJrCK59Gzg0hGep5OXDIvQlFRYUxzeXPBVRxQnkpLB9H05a6KAytJkr@Ht9mEm/cvmc@zzK/8q189LX3@Cw "Java (JDK) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~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!](https://tio.run/##hc5NCoMwFATgfU/xhC4STCQvIvYvnqC7LsVFwIrSGEu1NIJ3T0uFrgqZ7XwM0@rxdjXG@0aRiBKO9Ggjt7gCmTaGkELQpB9qcLSUSeI4Vsot84m72Cqjx4lwG@Oh5JbjYgtR0Wj2ve4sKKgHuD@ny/Q4W9jC2A4vIA3sBAOAfE838MsfhuLjUGCAZezbZAGWrywPraWSQSbT0Ld1TVL/Bg "Haskell – 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!](https://tio.run/##hc7NCoMwEATge59iBZEsGskqYn9InqC3HsVDwBZLYyzV0hx897RU6KmQuc7HML2ebmdjvL9IFiHjhAcbucUpShJtDGNKYD6MHThsijx3nFrpFlJCMqOnOWbcpoT7hltOi1WixYi51KIf9NWChG6E@3M@zY@jhRimfnwBu8BWZABQ73ADv/xhJD6OBAVYlX2bKsDqldWhtbLIoCrK0Ld1rUD/Bg "Haskell – 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 (!)
```
[Answer]
# [VDM-SL](https://raw.githubusercontent.com/overturetool/documentation/master/documentation/VDM10LangMan/VDM10_lang_man.pdf), 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*/
} 
)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
t:YqYk
```
[Try it online!](https://tio.run/##y00syfmfkPm/xCqyMDL7v0vIfwsDLkMDAy5TLksuU2MjLkMA "MATL – Try It Online")
List the first `n` primes and find the one closest to `n`.
[Answer]
# [Perl 5](https://www.perl.org/), 57 bytes
```
$a=0;while((1x$_)=~/^.?$|^(..+?)\1+$/){$_+=(-1)**$a*++$a}
```
[Try it online!](https://tio.run/##K0gtyjH9/18l0dbAujwjMydVQ8OwQiVe07ZOP07PXqUmTkNPT9teM8ZQW0Vfs1olXttWQ9dQU0tLJVFLQyVRW1uz9v9/IwMDAy4gwWUIwsZchpYW5lxmIEFLIDAHkxb/8gtKMvPziv/rFuTkAQA "Perl 5 – Try It Online")
`/^.?$|^(..+?)\1+$/` is tricky regexp to check prime
`(-1)**$a*++$a` generate sequence 0,-1, 2,-3 ...
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 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!](https://tio.run/##bcxBC4JAFATgu7@iS/Ae6OIqQeEqVOSpCLp4VnvqQm2wu8L66zc7lh3m8jEzrYlaI305qlZIZcM5xarLfZ8XJzU@SdfNg9itVj1BEiZC8BhZNZAmcH8qPHTIjq9RWZjywq0nwVGkyK76TvowfTaX2g5s3xhwUY/ISqmNBfRZEFRaWjpLRdDBNkbMvoTHC9r8wm7RSJPFzwz@DQ "C# (Visual C# Interactive Compiler) – Try It Online")
Left shifts by 20 in submission but 10 in TIO so that TIO terminates for test cases. 
]