Jump to content

Find squares n where n+1 is prime: Difference between revisions

Added AppleScript solutions.
(add RPL)
(Added AppleScript solutions.)
Line 24:
1 4 16 36 100 196 256 400 576 676
</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">on isPrime(n)
if (n < 4) then return (n > 1)
if ((n mod 2 is 0) or (n mod 3 is 0)) then return false
repeat with i from 5 to (n ^ 0.5) div 1 by 6
if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false
end repeat
return true
end isPrime
 
on task()
set output to {}
if (isPrime(1 * 1 + 1)) then set end of output to 1 * 1
repeat with sqrt from 2 to (1000 ^ 0.5) by 2
set n to sqrt * sqrt
if (isPrime(n + 1)) then set end of output to n
end repeat
return output
end task
 
task()</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{1, 4, 16, 36, 100, 196, 256, 400, 576, 676}</syntaxhighlight>
 
{{trans|Phix}}
The first Phix solution's method of incrementing the square is fun, but not more efficient in AppleScript than the more straightforward method above. It can be optimised slightly by incrementing the ''d'' variable by 8 instead of incrementing by 4 and multiplying the result by 2. Also by incrementing the square + 1 each time instead of the square itself, so that 1 only has to be subtracted from the hits instead of being added to every square.
<syntaxhighlight lang="applescript">on task()
set output to {1}
set nPlus1 to 5
repeat with d from 12 to (1000 ^ 0.5 div 0.25) by 8
if (isPrime(nPlus1)) then set end of output to nPlus1 - 1
set nPlus1 to nPlus1 + d
end repeat
return output
end task</syntaxhighlight>
 
=={{header|Arturo}}==
557

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.