Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- =begin
- The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
- There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
- How many circular primes are there below one million?
- detect primes less than one million
- check cirucularity
- rotate through all combination of digits in prime
- two digit:
- [0,1].join
- [1,0]
- three digits:
- [0,1,2]
- [2,0,1]
- [1,2,0]
- put string.last >> string[0], continue u
- check if each combination is also prime
- add to array of ciruclar primes
- calculate size of array
- =end
- class BaseProblemSolver
- def initialize(limit)
- @limit = limit
- end
- def solve
- circular_numbers = []
- primes_less_than(@limit).each do |prime|
- if circulars_of(prime).all? {|x| is_prime?(x)}
- circular_numbers << prime
- end
- end
- circular_numbers.size
- end
- def primes_less_than(num)
- range = [*2..num-1]
- range.select { |n| is_prime?(n)}
- end
- def is_prime?(num)
- array = [*2..num-1]
- array.all? do |n|
- num % n != 0
- end
- end
- def circulars_of(prime)
- results = []
- counter = 0
- prime_s = prime.to_s
- until counter == prime_s.size - 1
- prime_s = prime_s[1..prime_s.size] + prime_s[0]
- counter += 1
- results << prime_s.to_i
- end
- return results
- end
- end
- class FasterProblemSolver < BaseProblemSolver
- def initialize(limit)
- super(limit)
- @known_primes = []
- range = [*2..@limit - 1]
- range.delete_if do |n|
- # do the sieve
- end
- def is_prime?(num)
- known_primes.include?(num)
- end
- end
- CurrentSolver = BaseProblemSolver
- p CurrentSolver.new(100).solve
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement