# Palindromic Primes

Page 1 of 1

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

### #1 erik.price

• D.I.C Lover

Reputation: 486
• 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

Reputation: 128
• 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... :)