Skip to content

Instantly share code, notes, and snippets.

@p01
Forked from 140bytes/LICENSE.txt
Created July 30, 2011 11:27
Show Gist options
  • Save p01/1115434 to your computer and use it in GitHub Desktop.
Save p01/1115434 to your computer and use it in GitHub Desktop.
isPrimeNumber in 41 bytes
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>
@DivineGod
Copy link

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.

@mattneary
Copy link

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.

@tsaniel
Copy link

tsaniel commented Feb 28, 2012

@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.

@tsaniel
Copy link

tsaniel commented Feb 28, 2012

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment