Java 8, 83 bytes
n->n==1|p(n-1)+p(n)+p(n+1)>0int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return--n;}
Returns true
/ false
as truthy/falsey values.
Try it online.
Explanation:"
n-> // Method with integer parameter and boolean return-type
n==1 // Return whether the input is 1 (edge-case)
|p(n-1)+p(n)+p(n+1)>0// Or if the sum of `n-1`, `n`, and `n+1` in method `p(n)` is not 0
int p(int n){ // Separated method with integer as both parameter and return-type
for(int i=2;i<n; // Loop `i` in the range [2, `n`)
n=n%i++<1? // If `n` is divisible by `i`
0 // Change `n` to 0
: // Else:
n); // Leave `n` as is
// (After the loop `n` is either 0, 1, or unchanged,
// if it's unchanged it's a prime, otherwise not)
return--n;} // Return `n` minus 1
So int p(int n)
will result in -1
for n=0
and non-primes, and will result in n-1
for n=1
or primes. Since p(0)+p(1)+p(2)
will become -1+0+1 = 0
and would return false (even though 2
is a prime), the n=1
is an edge case using this approach.
A single loop without separated method would be 85 bytes:
n->{int f=0,j=2,i,t;for(;j-->-1;f=t>1?1:f)for(t=n+j,i=2;i<t;t=t%i++<1?0:t);return f;}
Returns 1
/ 0
as truthy/falsey values.
Try it online.
Explanation:
n->{ // Method with integer as both parameter and return-type
int f=0, // Result-integer, starting at 0 (false)
j=2,i, // Index integers
t; // Temp integer
for(;j-->-1; // Loop `j` downwards in range (2, -1]
f= // After every iteration: Change `f` to:
t>1? // If `t` is larger than 1 (`t` is a prime):
1 // Change `f` to 1 (true)
: // Else:
f) // Leave `f` the same
for(t=n+j, // Set `t` to `n+j`
i=2;i<t; // Inner loop `i` in the range [2, t)
t=t%i++<1? // If `t` is divisible by `i`:
0 // Change `t` to 0
: // Else:
t); // Leave `t` the same
// (If `t` is still the same after this inner loop, it's a prime;
// if it's 0 or 1 instead, it's not a prime)
return f;} // Return the result-integer (either 1/0 for true/false respectively)