Done puzzle 35
[project-euler.git] / euler35.rb
1 require 'ruby-prof'
2 load 'primes.rb'
3
4 class Array
5 def to_i
6 self.map {|d| d.to_s}.join.to_i
7 end
8
9 def to_r
10 Rational(self[0].to_i, self[1].to_i)
11 end
12
13 def all_rotations
14 (0...self.length).map {|r| self.rotate(r)}
15 end
16 end
17
18 class Integer
19 @@primes = Primes.instance
20
21 def prime?
22 @@primes.include? self
23 end
24
25 def pl
26 @@primes.primes.length
27 end
28
29 def circular_prime?
30 self.to_digits.all_rotations.map {|n| n.to_i}.all? {|n| n.prime?} if self.prime?
31 end
32
33 def to_digits
34 self.to_s.split('').map {|d| d.to_i}
35 end
36 end
37
38
39 (10**6).prime?
40
41 RubyProf.start
42
43 pl0 = 0.pl
44 beginning_time = Time.now
45 cps = (2..10**6).select {|n| n.circular_prime?}
46 end_time = Time.now
47 pl1 = 0.pl
48 puts "Time elapsed #{(end_time - beginning_time)} seconds, going from #{pl0} to #{pl1} primes cached"
49 puts cps.length
50
51 result = RubyProf.stop
52
53 printer = RubyProf::MultiPrinter.new(result)
54 printer.print(:path => ".", :profile => "profile")
55
56