Primality-testing function
The following 28-byte function returns true
for prime numbers and false
for non-primes:
f=(n,x=n)=>n%--x?f(n,x):x==1
This can easily be modified to calculate other things. For example, this 4139-byte function counts the number of primes less than or equal to a number:
f=(n,x=n)=>n?n%--x?f(n,x):(x==1)+f!--x+f(n-1):0
If you already have a variable n
that you want to check for primality, the primality function can be simplified quite a bit:
(f=x=>n%--x?f(x):x==1)(n)
How it works
f = ( // Define a function f with these arguments:
n, // n, the number to test;
x = n // x, with a default value of n, the number to check for divisibility by.
) =>
n % --x ? // If n is not divisible by x - 1,
f(n, x) // return the result of f(n, x - 1).
// This loops down through all numbers between n and 0,
// stopping when it finds a number that divides n.
: x == 1 // Return x == 1; for primes only, 1 is the smallest number
// less than n that divides n.
// For 1, x == 0; for 0, x == -1.
Note: This will fail with a "too much recursion" error when called with a sufficiently large input, such as 12345. You can get around this with a loop:
f=n=>eval('for(x=n;n%--x;);x==1')