Project Euler: Problems 1–20

Problem 1

Multiples of 3 and 5

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

object Problem1 {
  def solve: Int =
    (1 until 1000).filter(n => n % 3 == 0 || n % 5 == 0).sum
}

Problem 2

Even Fibonacci numbers

Each new term in the Fibonacci sequence is generated by adding the previous two terms. Starting with 1 and 2, the first 10 terms are: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89.

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

object Problem2 {
  def fibs: Stream[Int] =
    1 #:: 2 #:: zipWith(fibs, fibs.drop(1))(_ + _)

  def zipWith[A, B, C](as: Stream[A], bs: Stream[A])(f: (A, A) => C): Stream[C] =
    if (as.isEmpty || bs.isEmpty) Stream.empty
    else Stream.cons(f(as.head, bs.head), zipWith(as.tail, bs.tail)(f))

  def solve: Int =
    fibs.takeWhile(_ <= 4000000).filter(_ % 2 == 0).sum
}

Problem 3

Largest prime factor

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143?

object Problem3 {
  def largestPrimeFactor(n: Long): Long = {
    def loop(n: Long, d: Long): Long =
      if (d * d > n) n
      else if (n % d == 0) loop(n / d, d)
      else loop(n, d + 1)
    loop(n, 2)
  }

  def solve: Long = largestPrimeFactor(600851475143L)
}

Problem 4

Largest palindromic product

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

object Problem4 {
  import java.lang.StringBuilder

  def isPalindrome(n: Int): Boolean = {
    val s = n.toString
    s == new StringBuilder(s).reverse.toString
  }

  def solve: Int =
    (100 to 999).combinations(2).flatMap {
      case List(a, b) => List(a * b)
    }.filter(isPalindrome).max
}

Problem 5

Smallest multiple

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

object Problem5 {
  import scala.annotation.tailrec

  @tailrec
  def gcd(a: Int, b: Int): Int =
    if (b == 0) a else gcd(b, a % b)

  def lcm(a: Int, b: Int): Int = (a * b) / gcd(a, b)

  def solve: Int =
    (1 to 20).foldLeft(1)(lcm)
}

Problems 6–20

For problems 6 through 20, see the individual solution files.