Permalink
Browse files

fail fast, dont evaluate for primeness if even

  • Loading branch information...
1 parent 999da4b commit 452d4ede7e0281cb92b036c3626fbbc9ffb948a6 @jpsilvashy committed Mar 28, 2012
Showing with 29 additions and 2 deletions.
  1. +22 −0 ruby/my_math_lib.rb
  2. +7 −2 ruby/problem_007.rb
View
@@ -0,0 +1,22 @@
+module MyMathLib
+
+class Integer
+
+ # is the integer a prime number?
+ def is_prime?
+
+ # fail fast if even.
+ if self.even?
+ return false
+ end
+
+ for d in 2..(Math.sqrt(self))
+ if (self % d) == 0
+ return false
+ end
+ end
+ true
+ end
+
+end
+end
View
@@ -15,6 +15,12 @@ class Integer
# is the integer a prime number?
def is_prime?
+
+ # fail fast if even.
+ if self.even?
+ return false
+ end
+
for d in 2..(Math.sqrt(self))
if (self % d) == 0
return false
@@ -31,8 +37,7 @@ def is_prime?
primes_found = 0
until primes_found == 10_001 do
- if int.is_prime? && int != 2
- puts int
+ if int.is_prime?
primes_found += 1
end
int += 1

0 comments on commit 452d4ed

Please sign in to comment.