I'm currently doing the 5kyu "Master your primes: sieve with memoization" kata on Codewars. The challenge gives you a cached array of the first 4 prime numbers, and you must check if n (e.g. 5) is a prime in that array, if so, return true. If necessary (e.g. if n = 143), you must add primes to the cached array and stop when you get to n, then check if n is in the array (and hence a prime a number).
My code (below) is passing the tests for checking if prime or not. The problem is they've thrown in some strange inputs:
n = ($primes.size-5).abs<3 (test expects true)
n = ($primes.size-9).abs<3 (test expects true)
My code is currently only failing these 2 inputs. When I've evaluated them based on the where the cached array will be at that time, they both evaluate to false. The first line in my method attempts to return true if the value of n is false, I've tried this in 2 other ways also, nothing works so far.
Frustratingly, there's no mention whatsoever of these surprise tests in the kata description. As far as I'm aware the inputs ask "is the absolute value of the length of $primes minus 5 (and later 9), less than 3?"
Someone please explain to me if I'm wrong, what those inputs mean and how I can improve my code to pass these tests (and the kata).
require "prime"
$primes = [2,3,5,7]
def is_prime(n)
return true if n.class == FalseClass
return true if n <= $primes.max && $primes.include?(n)
($primes.max+1..n).each do |p|
next if !p.prime?
$primes << p
end
$primes.include?(n) ? true : false
end