Yan Cui

I help clients go faster for less using serverless technologies.

#### Problem

It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.

9 = 7 + 2×1^{2}

15 = 7 + 2×2^{2}

21 = 3 + 2×3^{2}

25 = 7 + 2×3^{2}

27 = 19 + 2×2^{2}

33 = 31 + 2×1^{2}

It turns out that the conjecture was false.

What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?

#### Solution

let hasDivisor(n) = let upperBound = int64(sqrt(double(n))) [2L..upperBound] |> Seq.exists (fun x -> n % x = 0L) // need to consider negative values let isPrime(n) = if n <= 1L then false else not(hasDivisor(n)) // generate the sequence of odd composite numbers let oddCompositeNumbers = Seq.unfold (fun state -> Some(state, state+2L)) 9L |> Seq.filter (fun n -> not(isPrime n)) // generate the sequence of prime numbers let primeNumbers = Seq.unfold (fun state -> Some(state, state+2L)) 1L |> Seq.filter isPrime // function to check if a number can be written as the sum of a prime and twice a square let isSum(number) = primeNumbers |> Seq.takeWhile (fun n -> n < number) |> Seq.exists (fun n -> sqrt(double((number-n)/2L)) % 1.0 = 0.0) let answer = oddCompositeNumbers |> Seq.filter (fun n -> not(isSum(n))) |> Seq.head

All pretty straight forward here, the only slightly confusing part of this solution is how to determine if a number can be written as the sum of a prime and twice a square:

Odd Composite Number = Prime + 2 x n^{2} => n = sqrt((Odd Composite Number – Prime) / 2)

As you know Math.Sqrt works with a double and returns a double, hence to find out if *n* above is a whole number I had to check whether it divides by 1 evenly

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

**Production-Ready Serverless**: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for**quickly levelling up your serverless skills**.- Do you want to know
**how to test serverless architectures**with a fast dev & test loop? Check out my latest course,**Testing Serverless Architectures**and learn the smart way to test serverless. - I help clients
**launch product ideas**,**improve their development processes**and**upskill their teams**. If you’d like to work together, then let’s**get in touch**. **Join my community on Discord**, ask questions, and join the discussion on all things AWS and Serverless.