Java 8, 83 byte
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;}
Restituisce true
/ false
come valori di verità / falsità.
Provalo online.
Spiegazione: "
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
Quindi int p(int n)
comporterà -1
per n=0
e non primi e comporterà n-1
per n=1
o primi. Dap(0)+p(1)+p(2)
diventerà-1+0+1 = 0
e ritornerebbe falso (anche se 2
è un numero primo), n=1
è un caso limite usare questo approccio.
Sarebbe un singolo ciclo senza metodo separato 85 byte :
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;}
ritorna 1
/ 0
come valori di verità / falsità.
Provalo online.
Spiegazione:
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)