Tim Varley Logo
Tim Varley Systems Engineer
Problem #36 hard

Double-base Palindromes

The decimal number, 585=10010010012585 = 1001001001_2 (binary), is palindromic in both bases.

Find the sum of all numbers, less than one million, which are palindromic in base 1010 and base 22.

Implementations

cpp
// Answer: 872187
// Authored by: Tim Varley 💘
// Assisted-by: Grok Code Fast via Crush 💘 <crush@charm.land>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
bool is_palindrome(const std::string& s) {
std::string rev = s;
std::reverse(rev.begin(), rev.end());
return s == rev;
}
long long double_base_palindromes() {
long long sum = 0;
for(int n=1; n<1000000; n++) {
std::string dec = std::to_string(n);
if(!is_palindrome(dec)) continue;
std::string bin = "";
int temp = n;
while(temp > 0) {
bin += (temp % 2) + '0';
temp /= 2;
}
std::reverse(bin.begin(), bin.end());
if(is_palindrome(bin)) sum += n;
}
return sum;
}
#if ! defined UNITTEST_MODE
int main(int argc, char const *argv[]) {
std::cout << double_base_palindromes() << std::endl;
}
#endif // UNITTEST_MODE

Solution Notes

Mathematical Background

A palindromic number reads the same forwards and backwards in a given base. A double-base palindrome is palindromic in both decimal (base 10) and binary (base 2).

For example, 585₁₀ = 1001001001₂, both palindromic.

Algorithm Analysis

The implementations use brute force enumeration:

  • Iterate through all numbers from 1 to 999,999
  • Convert each number to string (decimal) and check if palindromic
  • Convert to binary string and check if palindromic
  • Sum numbers that satisfy both conditions

Palindrome checking uses string reversal comparison.

Performance Analysis

  • Time Complexity: O(n × d) where n=10⁶ and d=20 (max digits), resulting in ~2×10⁷ operations. Executes in milliseconds on modern hardware.
  • Space Complexity: O(1) - only current number and strings stored.
  • Execution Time: Very fast (under 1 second), suitable for real-time applications.
  • Scalability: Linear in n, but could be optimized by generating palindromes directly.

Key Insights

  • Sum of double-base palindromes below 1,000,000 is 872,187
  • Single-digit numbers (1-9) are trivially palindromic in both bases
  • Binary palindromes often correspond to numbers with specific bit patterns
  • Leading zeros are not considered in either base representation

Educational Value

This problem teaches:

  • Number representation in different bases
  • String manipulation and palindrome detection
  • The concept of numerical bases beyond decimal
  • Brute-force enumeration with multiple conditions
  • Bit manipulation and binary number properties