1. $primes = []
  2.  
  3. def read_primes_from_file file_loc
  4. primes_unparsed = File.new(file_loc, "r")
  5. primes_up_str = primes_unparsed.gets
  6. primes_as_strs = primes_up_str[1...-2].split(" ")
  7. $primes = primes_as_strs.collect { |prime| prime.to_sym }
  8. primes_as_strs = nil
  9. primes_up_str = nil
  10. primes_unparsed.close
  11. primes_unparsed = nil
  12. end
  13.  
  14. def is_prime n
  15. return false if (0..1).include? n
  16. $primes.each { |prime| return false if n%prime == 0}
  17. true
  18. end
  19.  
  20. def prime_check n
  21. $primes.include? n
  22. end
  23.  
  24. def find_from_to first, last
  25. (first..last).each { |num| $primes << num if is_prime num }
  26. end
  27.  
  28. def is_circular_prime n
  29. num_str = n.to_s
  30. str_len = num_str.length
  31.  
  32. (0...str_len).each {|i|
  33. return false unless prime_check(num_str.to_sym)
  34. num_str = num_str[1..-1] + num_str[0...1]
  35. }
  36. true
  37. end
  38. p "Reading Primes From File"
  39. read_primes_from_file "primes.db"
  40. p "Read successfully. Last Prime: #{ $primes[0].to_s }"
  41.  
  42. p "Checking for Circular Primes"
  43. $primes.reverse!
  44. count_of_circ_primes = $primes.inject(0) { |count, prime|
  45. if is_circular_prime(prime)
  46. print "."
  47. count += 1
  48. else
  49. count
  50. end
  51. }
  52.  
  53. p count_of_circ_primes