diff --git a/nth-prime/example.rb b/nth-prime/example.rb index 923ebda9b3..6a8f1b1152 100644 --- a/nth-prime/example.rb +++ b/nth-prime/example.rb @@ -1,5 +1,3 @@ -require 'prime' - class Prime def self.nth(n) if n < 1 @@ -11,8 +9,17 @@ def self.nth(n) i = 1 while primes < n i += 1 - primes += 1 if Prime.prime?(i) + primes += 1 if self.prime?(i) end i end + + def self.prime?(n) + return false if n == 1 + return true if n == 2 + (2..Math.sqrt(n).ceil).each do |i| + return false if n % i == 0 + end + return true + end end diff --git a/nth-prime/nth_prime_test.rb b/nth-prime/nth_prime_test.rb index 9034de1078..8dfdbc75fe 100644 --- a/nth-prime/nth_prime_test.rb +++ b/nth-prime/nth_prime_test.rb @@ -1,4 +1,21 @@ require 'minitest/autorun' + +require 'prime' +Error_message = "Using Ruby's Prime class is probably the best way to do this in a 'real'\n" + + "application; but this is an exercise, not a real application, so you're\n" + + "expected to implement this yourself ;-)" +class Prime + [:each, :new, :prime?, :take].each do |m| + define_method(m) { |*_| raise Error_message } + end +end + +class Integer + [:prime?, :each_prime].each do |m| + define_method(m) { |*_| raise Error_message } + end +end + require_relative 'nth_prime' class TestPrimes < Minitest::Test