I am currently doing project 4 of Euler where I have to find the highest palindrome number. My idea was to put all the multiples into an array called multiples and change each of these numbers into a string.
Next I was going to loop though this array and push any string that was equal to its reverse to a new array called palindromes. However, for some reason my if statement evaluates for true for every number and I do not know why.
The specific code giving the problem is this
multiples.each do |n| #collecting the number of pallidromes
if n.reverse!.to_i == n.to_i#compare the number
palindromes.push(n)
end
end
The whole of the code is as follows:
#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
def palindrome(bigNum,smallNum)
i = 1
palindromes = []
multiples = []#collecting the number of multiples
while i <= bigNum
while smallNum <= bigNum
multipliedNum = bigNum * smallNum #multiplying each bigNum by each smallNum
multipliedNum = multipliedNum.to_s #changing it into a string
multiples.push(multipliedNum) #adding it an array
smallNum += 1
end
i += 1
end
multiples.each do |n| #collecting the number of pallidromes
if n.reverse!.to_i == n.to_i#compare the number
palindromes.push(n)
end
end
puts palindromes.inspect
puts palindromes.count
puts multiples[-1]
end
palindrome(999,100)
Any help is appreciated. Thanks
Aucun commentaire:
Enregistrer un commentaire