marlonmisra - 1 year ago 159
Ruby Question

# Problems writing a script that outputs first 100 palindromic primes

I wrote this script to find the first 100 primes that are also palindromes. For some reason some primes are not being printed (13, 17, etc.), and the palindromic function does not seem to work. Any tips?

``````#palindrome checker
def is_palindrome?(number)
number == number.to_s.reverse.to_i
end

#primes will consists of all primes starting with 2
#i will be incrememented and each i will be checked for being prime
primes = [2]
i = 3

#we only want the first 100 palindromic primes
while primes.length < 100
#test is false for a prime
test = false
#checks if i is divisible by any of the elements in the array
primes.each { |n|
if i % n == 0
test = true
end
}
#if i is prime that it is added to the primes array
if test == false
primes.push(i)
end
i += 1
end

#remove all non palindromic primes
primes.each { |n|
if is_palindrome?(n) == false
primes.delete(n)
end
}

#puts palindromic primes
puts primes
``````

I got it to work by changing your script to this:

``````#palindrome checker
def is_palindrome?(number)
number == number.to_s.reverse.to_i
end

#primes will consists of all primes starting with 2
#i will be incrememented and each i will be checked for being prime
primes = [2]
i = 3

#we only want the first 100 palindromic primes
while primes.length < 100
#test is false for a prime
test = false
#checks if i is divisible by any of the elements in the array
primes.each { |n|
if i % n == 0
test = true
end
}
#if i is prime that it is added to the primes array
if test == false
primes.push(i) if is_palindrome?(i) # This is the line I changed
end
i += 1
end

#puts palindromic primes
puts primes
``````

You were getting weird errors by modifying and iterating over your the `primes` array at the same time. I moved the palindrome check to inside the while loop so you will actually get 100 palindromes vs. 100 primes minus the non-palindromes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download