Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Distinct Powers

Consider all integer combinations of \(a^{b}\) for \(2 \leq a \leq 5\) and \(2 \leq b \leq 5\):

\begin{array}{rrrr} 2^{2}=4, &2^{3}=8, &2^{4}=16, &2^{5}=32\\ 3^{2}=9, &3^{}=27, &3^{4}=81, &3^{5}=243\\ 4^{2}=16, &4^{3}=64, &4^{4}=256, &4^{5}=1024\\ 5^{2}=25, &5^{3}=125, &5^{4}=625, &5^{5}=3125 \end{array}

Solution

Sometimes, the best solution is the simplest one. Due to Scala’s expressiveness this problem can be solved in a very concise way. All we need to do is to calculate all the powers, find the distinct ones, return the result. Just as the description says, no fancy tricks of any sort.

object Euler029 extends EulerApp {

  override def execute(): Any = {
    val results = for {
      a <- 2 to 100
      b <- 2 to 100
    } yield BigInt(a).pow(b)

    results.distinct.length
  }

}

Straightforward, easy to understand, very short and relatively fast.