Project Euler – Problem 36 Solution

Yan Cui

I help clients go faster for less using serverless technologies.

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.


 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


Leave a Comment

Your email address will not be published. Required fields are marked *