Skip to main content
3 of 4
golfed 7 bytes
ETHproductions
  • 50.1k
  • 6
  • 94
  • 240

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 41-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(n-1):0

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.

ETHproductions
  • 50.1k
  • 6
  • 94
  • 240