How to sum the digits of the number 2^N in Scala

1 Answer

0 votes
object PowerDigitSum {
  def sumOfDigits(n: Int): Int = {
    val power = BigInt(2).pow(n)
    power.toString.map(_.asDigit).sum
  }

  def main(args: Array[String]): Unit = {
    val testCases = List(15, 100, 1000)
    for (n <- testCases) {
      println(s"Sum of digits of 2^$n is: ${sumOfDigits(n)}")
    }
  }
}




/*
run:
 
Sum of digits of 2^15 is: 26
Sum of digits of 2^100 is: 115
Sum of digits of 2^1000 is: 1366
 
*/
 

 



answered Aug 2, 2025 by avibootz
...