1 Replies - 2121 Views - Last Post: 03 December 2009 - 01:48 AM

#1 erik.price   User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Palindromic Primes

Posted 01 December 2009 - 05:51 PM

Description: You could use the method of %=10 /=10 to reverse the number, but I went for the easier, built in way of making it a string, reversing it and changing it to an integer again Checks to see if a number is a palindromic prime (it is a prime number both forward and reversed, like 131, 5, and 101)
def isPrime?(n) #included to allow to check for primes
 unless n % 2 == 0
      i = 3
      while(i < n)
        if n % i == 0
          return false
        end
        i += 2
      end
      return true
    end
  end

def palPrime?(num)
  if num.to_s.reverse.to_i.==num
    if isPrime?(num)
      return true
    else
      return false
    end
    else
      return false
    end
end

#Example usage:
puts palPrime?(131) #=> true



Is This A Good Question/Topic? 0
  • +

Replies To: Palindromic Primes

#2 EdwinNameless   User is offline

  • D.I.C Addict
  • member icon

Reputation: 128
  • View blog
  • Posts: 723
  • Joined: 15-October 09

Re: Palindromic Primes

Posted 03 December 2009 - 01:48 AM

Ruby prime division is notoriously slow, but this can be reduced to:
require 'mathn.rb'

def palPrime?(num)
  pd = num.prime_division
  num.to_s.reverse == num.to_s and pd.size == 1 and pd[0][0] == num
end

puts palPrime?(131) #=> true

Obviously, this leaves out some optimizations... :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1