Euler Problem 36 asks:
‘is palindromic in both bases.
‘Find the sum of all numbers, less than one million, which
‘are palindromic in base 10 and base 2.
‘(Please note that the palindromic number, in either base,
‘may not include leading zeros.)
A palindrome reads the same left-to-right as right-to-left. Examples are “Able was I ere I saw Elba” and “A man, a plan, a canal. Panama”, and for Euler-purposes, 585. Project Euler, when discussing hints, says to read the details of the problem carefully. In this problem, there is a big hint.
Not including leading zeros means no ending zeros. In base 10, then there are no palindromic even multiples of ten. In base 2, there are no palindromic evens at all.
Here is my code. It runs in a few tenths of a second.
Dim i As Long
Dim Min As Long
Dim Max As Long
Dim IsTest As Boolean
Dim t As Single
Dim Answer As Long
Dim Dec As String
Dim Dec_rev As String
Dim Bits As String
Dim Bits_rev As String
t = Timer
IsTest = False
If IsTest Then
Min = 585
Max = 585
Min = 1
Max = 999999 ‘ Less than 1000000
For i = Min To Max Step 2 ‘Even numbers need not apply…
Dec = CStr(i)
Dec_rev = VBA.StrReverse(Dec)
If Dec = Dec_rev Then
Bits = LongToBit04(i) ‘returns a 32-bit string
While Left(Bits, 1) = “0” ‘stripping leading zeros
Bits = Mid(Bits, 2, Len(Bits) – 1)
Bits_rev = VBA.StrReverse(Bits)
If Bits = Bits_rev Then
Answer = Answer + i
Debug.Print Answer; ” Time:”; Timer – t
Function LongToBit04(ByVal lLong As Long) As String
‘ by Don/Egbert, 20001222
Dim i As Long
LongToBit04 = String$(32, 48) ’48 = “0”
‘ handle sign bit
If lLong And &H80000000 Then
Mid$(LongToBit04, 1, 1) = “1”
lLong = lLong And Not &H80000000
For i = 32 To 2 Step -1
If lLong And 1 Then Mid$(LongToBit04, i, 1) = “1”
lLong = lLong 2 ‘shift right
It takes the decimal number as a string and reverses it. If they are equal, then they are palindromic. For these cases, it turns the decimal via LongToBit04() into a 32-bit binary, strips the leading zeros, and reverses that. Again if equal, it adds to the running sum.
The LongToBit04() function comes from the people over at VBSPEED, “The Visual Basic Performance Site” at http://www.xbeat.net/vbspeed/. Over there they rack and stack algorithms for dozens of purposes. They score 10 different longs-to-bits schemes, for instance, and #4 isn’t even the fastest. The site doesn’t seem to be as active as it once was, but it’s a great resource still.