Made the primes library faster
authorNeil Smith <neil.git@njae.me.uk>
Thu, 16 Feb 2017 14:04:29 +0000 (14:04 +0000)
committerNeil Smith <neil.git@njae.me.uk>
Thu, 16 Feb 2017 14:04:29 +0000 (14:04 +0000)
euler35.rb
primes.rb

index ebe845009339585d798af3186c3c5414d3c2c02d..d2ba75de75e1c1c3c738cefe8c6ac937f57765a7 100644 (file)
@@ -36,10 +36,11 @@ class Integer
 end 
 
 
-(10**6).prime?
-
 RubyProf.start
 
+# (10**6).prime?
+
+
 pl0 = 0.pl
 beginning_time = Time.now
 cps = (2..10**6).select {|n| n.circular_prime?}
index 0febe8007f617dd2b3ecbca2eae02a72ef41cd57..23fd44737758478dfe7cad13b159755b3f94a9c9 100644 (file)
--- a/primes.rb
+++ b/primes.rb
@@ -28,7 +28,9 @@ class Primes
 
   def next_prime
     candidate = next_candidate(@primes[-1])
-    while @primes.any? {|i| candidate % i == 0 }
+    limit = Math.sqrt(candidate).floor
+    index = @primes.bsearch_index {|i| i > limit} || @primes.length
+    while @primes[0..index].any? {|i| candidate % i == 0 }
       candidate = next_candidate(candidate)
     end
     candidate
@@ -90,10 +92,11 @@ class Primes
   end
   
   def include?(n)
-    while n >= @primes.max
+    while n >= @primes.last
       add_next_prime!
     end
-    @primes.include?(n)
+    # @primes.include?(n)
+    !!(@primes.bsearch {|i| n - i})
   end
 
 end