g | x | w | all
Bytes Lang Time Link
012Vyxal 3240918T191803ZGinger
011Brachylog240917T095632ZFatalize
052R240726T105056Zpajonk
093Bash240726T135229ZThemooni
076R240726T071436Zint 21h
056JavaScript Node.js240726T083830Zl4m2
015Husk201010T162303ZRazetime
047Regex most flavors190329T172858ZGrimmy
081Python 2170904T043332Zmiles
064Julia 0.6170710T051234ZTanj
022braingasm170710T174539Zdaniero
098JavaScript170710T023910Ztraktor
078GNU APL 1.2170709T142212ZArc676
013MATL170708T170932ZLuis Men
154JavaScript ES6170708T200434ZЕвгений
092Python 2170708T211633ZChas Bro
120Python 2.7170708T213816ZJoe Habe
041Perl 6170708T210521ZSean
149Python 3170708T185426Zwrymug
069PHP170708T204038ZJör
042Maxima170708T175357Zrahnema1
053Octave170708T174717Zrahnema1
084Octave170708T165141ZSteadybo
015Pyth170708T172204ZErik the
009Jelly170708T164951ZJonathan
01705AB1E170708T170342ZErik the
007Jelly170708T165341ZPurkkaKo
009Jelly170708T164144ZErik the
024Mathematica170708T164123ZMartin E

Vyxal 3, 12 bytes

ÞP$Ḟ∦ꜝvqⁿ⁰ȧ>

Vyxal It Online!

Brachylog, 11 bytes

{;I≜+ṗ}ᶠ²>₁

Try it online!

Explanation

This exploits the fact that for an unconstrained integer variable, when trying possible values, it will try them in this order: {0, 1, -1, 2, -2, 3, -3, …}. Therefore, if we add such a variable to the input, the first prime result it will find will be the closest. We then check if it’s bigger or smaller than the input.

{     }ᶠ²     Find the first two solutions of:
 ;I≜            Take any integer I: 0, or 1, or -1, or 2, or -2, etc.
    +ṗ          Input + I is prime
         >₁   The first solution (Input + 0) is greater than the second

R, 52 bytes

`?`=\(n,i=1,k=n+i)`if`(sum(!k%%2:k)<2,i<0,n?(i<0)-i)

Attempt This Online!


R, 64 bytes

\(n,m=sapply(n+n:-n,\(x)x/(sum(!x%%2:x)<2))-n)m[order(m^2)[2]]<0

Attempt This Online!

No recursion or loops.

Bash, 93 bytes

n()(for((i=$1;`factor $i|wc -w`>2;i+=$2)){
:;}
echo $i)
((`n $[$1+2] 2`+`n $[$1-2] -2`>2*$1))

Attempt This Online!

uses coreutils' factor.

Use as bash script or body of a bash function, takes in n as first argument and exit code is set truthy if n is a weak prime, falsey otherwise.

explanation:

n()(                                      #define a new function called n
    for((i=$1;`factor $i|wc -w`>2;i+=$2)){ #a for loop that finds the next prime after $1, moving in steps of $2
:;} #(notice this allows for finding previous primes too by setting $2 to -2.)
echo $i) #echo the found prime, end function declaration
((`n $[$1+2] 2`+`n $[$1-2] -2`>2*$1)) #test if prevPrime(n) + nextPrime(n) > 2n, using our function and feeding it n+2,2 and n-2,-2 as parameters.
#implicit: function or script exit code is set as the exit code of the last command.

R, 77 76 bytes

\(n,x=2:n^2,d=diff(a<-x[mapply(\(j)sum(!j%%x)<2,x)]))d[w<-match(n,a)]>d[w-1]

Attempt This Online!

Outputs TRUE for the weak primes, FALSE for the non-weak and a NA for the composite numbers.

Ungolfed and commented:

\(n){

# construct a vector from 2 to n^2,
# which includes the next prime number
x <- 2:n^2                       

# find the prime numbers: 
m <- mapply(\(j)sum(!j%%x)<2, x) 

# subset to the prime numbers only
a <- x[m]                        

# calculate a vector of the differences 
d <- diff(a)                    

# find the position of n in the vector of the primes 
w <- match(n,a)                 

# compare two differences
d[w] > d[w-1]                    
}

JavaScript (Node.js), 56 bytes

f=(x,i=1)=>P(e=x+i)?i<0:f(x,(i<0)-i)
P=x=>e%--x?P(x):x<2

Try it online!

Nothing

Husk, 15 bytes

>D¹Σ§e₁←₁→
ḟṗt¡

Try it online!

Regex (most flavors), 47 bytes

^(?=(x*)(?!(x+)(\2\2x)+$)\1)x+(?!(xx+)\4+$)\1\1

Try it online!

Takes input in unary. Outputs a match for weak primes, no match for non-weak primes. Works in ECMAScript, Perl, PCRE, Python, Ruby.

Explanation:

Let N be the input, A the closest prime < N, and B the closest prime > N. The main difficulty of a regex approach to this challenge is that we can’t represent numbers greater than the input, like B. Instead, we find the smallest b such that 2b + 1 is prime and 2b + 1 > N, which ensures 2b + 1 = B.

(?=
  (x*)              # \1 = N - b, tail = b
  (?!(x+)(\2\2x)+$) # Assert 2b + 1 is prime
  \1                # Assert b ≥ \1 (and thus 2b + 1 > N)
)

Then, note that we don’t actually need to find A. As long as any prime < N is closer to N than B, N is a weak prime.

x+                  # tail iterates over integers < N
(?!(xx+)\4+$)       # assert tail is prime
\1\1                # assert tail ≥ 2 * \1 (and thus tail + B > 2N)

Python 2, 81 bytes

n=input()
a=b=c=i=2;p=1
while b<n:
 p*=i;i+=1
 if p*p%i:a,b,c=b,c,i
print a+c>2*b

Try it online!

Uses Wilson's theorem for the primality test.

Julia 0.6, 64 bytes

g(x,i)=0∉x%(2:x-1)?1:1+g(x+i,i);x->g(x,1)&(g(x-1,-1)<g(x+1,1))

braingasm, 23 22 bytes

Prints 1 for weak primes and 0 for not weak.

;>0$+L[->+>2[>q[#:Q]]]

Walkthrough:

;                       Read a number to cell 0
 >0$+                   Go to cell 1 and copy the value of cell 0
     L                  Make the tape wrap around after cell 1
      [              ]  Loop:
       ->+>               Decrease cell 1 and increase cell 0
           2[       ]     Twice do:
             >              Go to the other cell
              q[   ]        If it's prime:
                #:Q         Print the current cell number and quit

JavaScript, 98 bytes

let test = _=>(o.innerHTML=f(+prime.value))
let f= 

n=>{P=n=>{for(i=n,p=1;--i>1;)p=p&&n%i};a=b=n;for(p=0;!p;P(--a));for(p=0;!p;P(++b));return n-a<b-n}
Enter Prime: <input id="prime">
<button type="button" onclick="test()">test if weak</button>
<pre id="o"></pre>

Less Golphed

n=>{
   P=  // is a Prime greater than 1, result in p
       n=>{
           for(i=n,p=1;--i>1;)
               p=p&&n%i
       };

   a=b=n; // initialize lower and upper primes to n
   for(p=0;!p;P(--a)); // find lower,
   for(p=0;!p;P(++b)); // find upper,
   return n-a<b-n // is weak result
}

Note the test code does not check the input "prime" is actually a prime.

GNU APL 1.2, 78 bytes

∇f N
X←(R←(~R∊R∘.×R)/R←1↓⍳N×2)⍳N
(|R[X-1]-N)<|R[X+1]-N
∇

∇f N declares a function that takes an argument.

(~R∊R∘.×R)/R←1↓⍳N×2 gives a list of all the primes from 2 to twice the argument. I'm assuming that the next prime is less than twice the original. If this is untrue, N*2 gives N squared and takes the same number of bytes (hopefully that's big enough to exceed the next prime). (See Wikipedia's explanation for how the prime-finding works)

X←(R←(...))⍳N assigns that list to vector R (overwriting its previous contents), finds the index of the original prime N in that list, and then assigns that index to X.

|R[X-1]-N computes the difference between the previous prime (because R contains the primes, the X-1th element is the prime before N) and N and then takes the absolute value (APL operates right-to-left).

|R[X+1]-N does the same, but for the next prime.

(|R[X-1]-N)<|R[X+1]-N prints 1 if the previous prime is closer to the original than the next prime and 0 otherwise. Parentheses are needed for precedence.

ends the function.

MATL, 13 bytes

qZq0)G_Yq+GE>

This outputs 1 if weak, 0 otherwise.

Try it online!

Explanation

q      % Implicit input, Subtract 1
Zq     % Vector of primes up to that
0)     % Get last one
G      % Push input again
_Yq    % Next prime
+      % Add
G      % Push input
E      % Multiply by 2
>      % Greater than? Implicit display

JavaScript ES6, 162 154 bytes

8 bytes save based on Jörg Hülsermann's trick "print nothing in one case". No need to ?"Y":"N" after one<two

var isWeak=

a=>{p=[2];i=0;f=d=>{j=p[i];l:while(j++){for(x=0;p[x]*p[x]<=j;x++){if(j%p[x]==0){continue l}}return p[++i]=j}};while(p[i]<a+1){f()};return a*2<p[i]+p[i-2]}

[43,//true
53,//false
7901,//false
7907,//true
1299853,//true
1299869//false
].forEach(n=>{console.log(n,isWeak(n))})

Python 2, 122 108 103 94 92 bytes

def a(n):
 r=[2];x=2
 while r[-1]<=n:x+=1;r+=[x]*all(x%i for i in r)
 return sum(r[-3:])>3*n

Try it online!

Uses Pietu's idea... and then saved 28 bytes by golfing shorter prime list iterators; then 2 more by replacing -3*n>0 with >3*n (d'oh!)

Python 2.7 - 120 bytes

from math import*
i=lambda x:factorial(x-1)%x==x-1
def f(n,c):return 1 if i(n-c)>i(n+c) else 0 if i(n+c)>0 else f(n,c+1)

Since python doesn't have a built-in is prime function, we can use Wilson's theorem to get a nice short prime checker. Wilson's theorem states that a number is prime if and only if (n-1)! is congruent to -1 mod(n). Hence the function i will return 1 if the number is prime and 0 if it's not. Following that the f function will determine if the next prime from that number occurs first when incremented down rather than incremented up. If neither of the incremented numbers prime, it's just recursively called again.

Some example I/O

f(3,1)
1
f(15,1)
0

Perl 6, 41 bytes

{[>] map ->\n{$_+n,*+n...&is-prime},1,-1}

Try it online!

$_ is the argument to the function. The mapping function -> \n { $_ + n, * + n ... &is-prime } takes a number n and returns a sequence of numbers $_ + n, $_ + 2*n, ... that ends when it reaches a prime number. Mapping this function over the two numbers 1 and -1 produces a sequence of two sequences; the first starts with $_ + 1 and ends with the first prime number greater than $_, and the second starts with $_ - 1 and ends with the first prime number less than $_. [>] reduces this two-element list with the greater-than operator, returning true if the first sequence is greater (ie, longer) than the second.

Python 3, 149 bytes

f=lambda n,k=1,P=1:n*[0]and P%k*[k]+f(n-P%k,k+1,P*k*k)
def a(n):p=f(n);return p.index(n)in filter(lambda i:p[i]-p[i-1]<p[i+1]-p[i],range(1,len(p)-1))

Try it online!

I'm using a prime generating function (top line) taken from this old stack exchange answer.

PHP, 69 bytes

prints one for weak prime and nothing for not weak prime

for(;!$t;$t=$d<2)for($n=$d=$argn+$i=-$i+$w^=1;$n%--$d;);echo$n<$argn;

Try it online!

Maxima, 42 bytes

f(n):=is(n-prev_prime(n)<next_prime(n)-n);

Try it online!

Octave, 53 bytes

@(n)diff(list_primes(h=nnz(primes(n))+1)(h-2:h),2)>0

Try it online!

Octave, 93 84 bytes

Thanks to @LuisMendo and @rahnema1 for saving bytes!

function r=f(x);i=j=x;do--i;until(i<1|isprime(i));do++j;until(isprime(j));r=x-i<j-x;

Try it online!

Pyth, 15 bytes

>-fP_ThQfPT_tQy

Try it here.

Uses Pietu1998's algorithm.

Jelly, 9 bytes

ḤÆRạÞ⁸ḊḢ>

Returns 1 for weak and 0 for not weak or balanced (returns 1 for an input of 2)

Try it online!

How?

ḤÆRạÞ⁸ḊḢ> - Link: prime number > 2, p
Ḥ         - double -> 2*p
 ÆR       - yield primes between 2 and 2*p inclusive
     ⁸    - chain's left argument, p
    Þ     - sort by:
   ạ      -   absolute difference (i.e. distance from p)
      Ḋ   - dequeue (removes p from the list, since it has distance zero)
       Ḣ  - head (gives us the nearest, if two the smallest of the two)
        > - greater than p?

05AB1E, 17 bytes

[<Dp#]¹[>Dp#]+¹·›

Try it online!

Uses Pietu1998's algorithm.

Jelly, 7 bytes

Æn+Æp>Ḥ

Try it online!

Explanation

           See if
Æn         the next prime
  +Æp      plus the previous prime
     >Ḥ    is greater than 2n

As a bonus, changing > to = or < checks for balanced and strong primes, respectively.

Jelly, 9 bytes

Æp;;ÆnI</

Try it online!

Mathematica, 24 bytes

n=NextPrime;2#+n@-#<n@#&

The NextPrime built-in can be (ab?)used to compute the previous prime by feeding it a negative argument.