Oxaric’s Blog

A compendium of amazing things…

Euler Project Problem #35 Solution

Posted by oxaric on November 24, 2008

It uses Ruby.


Click to directly download euler-solution-35.rb

# filename 'euler-solution-35.rb'
# By: Louis Casillas, oxaric@gmail.com

# Euler Problem #35
# How many circular primes are there below 1 million

def isPrime( num )
   if (num == 2) || (num == 3)
      return true
   end

   if ((num % 2) == 0 )
      return false
   end
   
   if ((num % 3) == 0 )
      return false
   end

   r = Math.sqrt( num ).floor
   f = 5

   while (<= r)
      if ((num % f) == 0)
         return false
      end

      if ((num % (+ 2)) == 0)
         return false
      end

      f += 6
   end

   true
end

def rotateNumber( num )
   num_s = num.to_s
   
   temp = num_s[0]   

   for i in (1...num_s.size)
      num_s[ i - 1] = num_s[ i ]
   end

   num_s[ num_s.size - 1 ] = temp

   return num_s.to_i
end

=begin
2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933
=end

MAX = 1000000

= 3

#array_of_circular_primes = Array.new
#array_of_circular_primes.insert( 0, 2 )
is_circular_prime = true
num_of_circular_primes = 1

while ( i < MAX )

   if isPrime( i )
      temp_s = i.to_s
      if ( !temp_s.include?( "2" ) &&
                     !temp_s.include?( "4" ) &&
           !temp_s.include?( "6" ) &&
           !temp_s.include?( "8" )
                   )
         temp = rotateNumber( i )
         
         1.upto(i.to_s.size - 1) do
      
            if !isPrime( temp )
               is_circular_prime = false
            end

            temp = rotateNumber( temp )
         end

         if is_circular_prime
            #puts "Found a circular prime: " + i.to_s
   
            num_of_circular_primes += 1
         end
      end

      is_circular_prime = true
   end

   i += 2   
end

#array_of_circular_primes.uniq!

puts "There are this many circular primes below 1 million: " + num_of_circular_primes.to_s

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>