Project Euler – Problem 36 Solution

Problem

The decimal number, 585 = 10010010012 (binary), 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.)

Solution

open System
open System.Linq

// checks if the number n is palindromic in the supplied base b
let isPalindromic (b:int) (n:int) =
    let charArray = Convert.ToString(n, b).ToCharArray()
    let revCharArray = Array.rev charArray
    charArray.SequenceEqual(revCharArray)

// using function currying to build two higher-order functions to check
// if number is palindormic in base 10 and base 2 separately
let isPalindromicBase10 = isPalindromic 10
let isPalindromicBase2 = isPalindromic 2

let answer =
    [1..1000000]
    |> List.filter (fun n -> isPalindromicBase10 n && isPalindromicBase2 n)
    |> List.sum

The isPalindromic function here is an enhanced version of the one I first wrote for the problem 4 solution, with the added functionality to check if the number is palindromic in the specified base. Using the overloaded Convert.ToString method I was able to easily convert a given number to its binary representation and check if the number is palindromic in base 2.

If you aren’t familiar with functional languages like F#, you might also be curious as to how the isPalindromicBase10 and isPalindromicBase2 functions work. This is a form of function currying where you can create new functions by apply a subset of the required parameters to a base function, see here for more information and examples of this.

Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter


Hi, I’m Yan. I’m an AWS Serverless Hero and the author of Production-Ready Serverless.

I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.


Check out my new course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, callbacks, nested workflows, design patterns and best practices.

Get Your Copy