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;}
Retorna true
/ false
como valores de verdade / falsey.
Experimente online.
Explicação: "
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
Portanto int p(int n)
, resultará em -1
for n=0
e non-primos, e resultará em n-1
for n=1
ou primos. Como p(0)+p(1)+p(2)
se tornará -1+0+1 = 0
e retornaria falso (mesmo que 2
seja primo), esse n=1
é um caso extremo usando essa abordagem.
Um único loop sem método separado teria 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;}
Retorna 1
/ 0
como valores de verdade / falsey.
Experimente online.
Explicação:
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)