Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2016
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. =begin
  2. The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
  3.  
  4. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
  5.  
  6. How many circular primes are there below one million?
  7.  
  8.  
  9. detect primes less than one million
  10. check cirucularity
  11. rotate through all combination of digits in prime
  12. two digit:
  13. [0,1].join
  14. [1,0]
  15. three digits:
  16. [0,1,2]
  17. [2,0,1]
  18. [1,2,0]
  19.  
  20. put string.last >> string[0], continue u
  21.  
  22. check if each combination is also prime
  23. add to array of ciruclar primes
  24. calculate size of array
  25. =end
  26.  
  27.  
  28. class BaseProblemSolver
  29.  
  30. def initialize(limit)
  31. @limit = limit
  32. end
  33.  
  34. def solve
  35. circular_numbers = []
  36. primes_less_than(@limit).each do |prime|
  37. if circulars_of(prime).all? {|x| is_prime?(x)}
  38. circular_numbers << prime
  39. end
  40. end
  41. circular_numbers.size
  42. end
  43.  
  44. def primes_less_than(num)
  45. range = [*2..num-1]
  46. range.select { |n| is_prime?(n)}
  47. end
  48.  
  49. def is_prime?(num)
  50. array = [*2..num-1]
  51. array.all? do |n|
  52. num % n != 0
  53. end
  54. end
  55.  
  56. def circulars_of(prime)
  57. results = []
  58. counter = 0
  59. prime_s = prime.to_s
  60. until counter == prime_s.size - 1
  61. prime_s = prime_s[1..prime_s.size] + prime_s[0]
  62. counter += 1
  63. results << prime_s.to_i
  64. end
  65. return results
  66. end
  67. end
  68.  
  69. class FasterProblemSolver < BaseProblemSolver
  70. def initialize(limit)
  71. super(limit)
  72. @known_primes = []
  73. range = [*2..@limit - 1]
  74. range.delete_if do |n|
  75.  
  76.  
  77. # do the sieve
  78. end
  79.  
  80. def is_prime?(num)
  81. known_primes.include?(num)
  82. end
  83. end
  84.  
  85.  
  86. CurrentSolver = BaseProblemSolver
  87.  
  88. p CurrentSolver.new(100).solve
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement