28
\$\begingroup\$

A prime is weak if the closest other prime is smaller than it. If there is a tie the prime is not weak.

For example 73 is a weak prime because 71 is prime but 75 is composite.

Task

Write some computer code that when given a prime greater than 2 as input will determine if it is a weak prime. This is a standard so you should output two unique values for each of the two cases (e.g. weak and not weak).

This is so standard rules for the tag apply.

OEIS

Here are the first 47 weak primes:

3, 7, 13, 19, 23, 31, 43, 47, 61, 73, 83, 89, 103, 109, 113, 131, 139, 151, 167, 181, 193, 199, 229, 233, 241, 271, 283, 293, 313, 317, 337, 349, 353, 359, 383, 389, 401, 409, 421, 433, 443, 449, 463, 467, 491, 503, 509, 523, 547, 571, 577, 601, 619, 643, 647

Here is the OEIS for weak primes (should return weak) OEIS A051635

Here is the OEIS for balanced primes (should return not weak) OEIS A006562

Here is the OEIS for strong primes (should return not weak) OEIS A051634

\$\endgroup\$
2
  • \$\begingroup\$ not weak or strong? \$\endgroup\$ Commented Jul 8, 2017 at 16:39
  • 7
    \$\begingroup\$ @CalculatorFeline not weak is different than strong \$\endgroup\$
    – Wheat Wizard
    Commented Jul 8, 2017 at 16:39

29 Answers 29

27
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ That should be >, no? \$\endgroup\$
    – Dennis
    Commented Jul 8, 2017 at 16:55
  • 2
    \$\begingroup\$ Oh wow, that's clever... \$\endgroup\$ Commented Jul 8, 2017 at 16:55
  • \$\begingroup\$ I just worked this way out too. Nice work! \$\endgroup\$ Commented Jul 8, 2017 at 16:59
  • \$\begingroup\$ This is so clever... \$\endgroup\$ Commented Jul 8, 2017 at 17:06
12
\$\begingroup\$

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.

\$\endgroup\$
7
\$\begingroup\$

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?
\$\endgroup\$
5
  • \$\begingroup\$ Ninja'd me with a complex solution... \$\endgroup\$ Commented Jul 8, 2017 at 16:50
  • \$\begingroup\$ It was a split-second! \$\endgroup\$ Commented Jul 8, 2017 at 16:51
  • 1
    \$\begingroup\$ No it wasn't, it was 9 full seconds iirc. No, 10 seconds. \$\endgroup\$ Commented Jul 8, 2017 at 16:51
  • \$\begingroup\$ So it was (looking at the times) it happened as I submitted here :) \$\endgroup\$ Commented Jul 8, 2017 at 16:52
  • 1
    \$\begingroup\$ Well, it seems you just golfed faster than me...(it's quite a trip to first go from IIṠ⁼1 to II>0 to I<\)...yours is much different though. It seems you think differently than me...EDIT: Pietu1998 returned! \$\endgroup\$ Commented Jul 8, 2017 at 16:53
5
\$\begingroup\$

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!

\$\endgroup\$
3
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ Can't you use i-=1 etc? Also, end is not needed in the function; you can move it to the footer \$\endgroup\$
    – Luis Mendo
    Commented Jul 8, 2017 at 17:10
3
\$\begingroup\$

Maxima, 42 bytes

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

Try it online!

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Jelly, 9 bytes

Æp;;ÆnI</

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Pyth, 15 bytes

>-fP_ThQfPT_tQy

Try it here.

Uses Pietu1998's algorithm.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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!)

\$\endgroup\$
2
\$\begingroup\$

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)
\$\endgroup\$
2
\$\begingroup\$

R, 77 76 bytes

  • -1 byte thanks to ovs
\(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]                    
}
\$\endgroup\$
0
1
\$\begingroup\$

Octave, 53 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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))})

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Husk, 15 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Vyxal 3, 12 bytes

ÞP$Ḟ∦ꜝvqⁿ⁰ȧ>

Vyxal It Online!

\$\endgroup\$
1
0
\$\begingroup\$

05AB1E, 17 bytes

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

Try it online!

Uses Pietu1998's algorithm.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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))
\$\endgroup\$
0
\$\begingroup\$

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.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.