41 bytes version initially golfed from @Georg_Tavonius entry ( http://twitter.com/#!/Georg_Tavonius/status/97239621959815170 )
-
-
Save p01/1115434 to your computer and use it in GitHub Desktop.
function( | |
n, // the number | |
i // placeholder counter | |
){ | |
for(i=n;n%--i;); // keeps going until the modulo is falsy like n%1 for instance | |
return i<2 | |
} |
function(n,i){for(i=n;n%--i;);return i<2} |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
Version 2, December 2004 | |
Copyright (C) 2011 Mathieu 'p01' Henri <http://www.p01.org/releases/> | |
Everyone is permitted to copy and distribute verbatim or modified | |
copies of this license document, and changing it is allowed as long | |
as the name is changed. | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION | |
0. You just DO WHAT THE FUCK YOU WANT TO. |
{ | |
"name": "isPrimeNumber", | |
"description": "Check if a number is prime in 41bytes.", | |
"keywords": [ | |
"isPrimeNumber", | |
"prime", | |
"number" | |
] | |
} |
<!DOCTYPE html> | |
<title>isPrimeNumber</title> | |
<div>Expected values: <b>false,true</b></div> | |
<div>Actual value: <b id="ret"></b></div> | |
<script> | |
var myFunction = function(n,i){for(i=n;n%--i;);return i<2}; | |
document.getElementById( "ret" ).innerHTML = myFunction(140)+','+myFunction(541); | |
</script> |
:D/ reversing the loop brought this puppy down to 46 bytes with the fix for the case 0 and 1
function(n,i){for(i=n;n%--i;);return n<2||i<2}
EDIT: Actually the n<2||
is not necessary anymore due the falsiness of x%1
and x%0
. And that, gentlemen, brings us to 41 bytes:
function(n,i){for(i=n;n%--i;);return i<2}
Nice!
But I think 0 and 1 shouldn't be identified as prime numbers.
Ref: http://oeis.org/A000040
return i==1
instead of return i<2
will return correctness of function at the expense of a byte.
42 is a nice number anyway.
If javascript could better handle large numbers this could be done in 30 bytes via Fermat's little theorem:
function(n){return(1<<n)%n==2}
Sadly, this function only works for numbers less than 30 due to the poor handling of math in JavaScript.
@mattneary: I think even JavaScript could handle large numbers, your code won't work.
Because some non-prime numbers (e.g. 341) can pass the test.
I mean the theorem cannot tell whether a number is really a prime number or not, 341 is an example(It passes the test even it is not a prime number).
Nice move putting the
n%i
inside the condition. Yaffle'si*i
speed optimization and fix for the case for 0 and 1 were a nice touch.Here's a 47 bytes version of Atk's golf:
function(n,i){for(i=1;n>++i&&n%i;);return i==n}
then a 55bytes version with Yaffle's improvements:
function(n,i){for(i=1;n>++i*i&&n%i;);return n<2||i*i>n}
And 52bytes with fixing the case for 0 and 1:
function(n,i){for(i=1;n>++i&&n%i;);return n<2||i==n}