At #railsclub @fxn told me about an amazing way of determining wheter the number is prime in different languages – using #regexp! This is really great technique at you can see how simple it is:

def isPrimeRegexp n
  "1" * n =~ /^1?$|^(11+?)\1+$/
end

There are quite a few algorithms for determining wheter the number is prime, there is a good wiki for it. So lets compare #regexp solution to the simplest algorithm using #benchmark_ips:

require 'benchmark/ips'

def isPrimeRegexp n
  "1" * n =~ /^1?$|^(11+?)\1+$/
end

def isPrime(number)
  if number == 0 or number == 1
    return false
  end

  i = 2
  limit = number / i
  while i < limit
    if number % i == 0
      return false
    end
    i += 1
    limit = number / i
  end
  return true
end

Benchmark.ips do |r|
  r.report('isPrimeRegexp') do
    isPrimeRegexp(131)
  end

  r.report('isPrime') do
    isPrime(131)
  end
end

# Calculating -------------------------------------
#        isPrimeRegexp      2434 i/100ms
#              isPrime     45790 i/100ms
# -------------------------------------------------
#        isPrimeRegexp    25621.3 (±1.6%) i/s -     129002 in   5.036280s
#              isPrime   898325.9 (±0.7%) i/s -    4533210 in   5.046548s

As you can see the regexp solution is not so fast but it is really short and I think that this approach of using regexp for some math is amazing because for many developers regexp is associated to strings and not for working numbers.

@fxn applied this technique for many more #math tricks so you can see all of them at https://github.com/fxn/math-with-regexps.

#ruby