Problem:
Prime Factorization

Factorize a given integer n.

Input

n

An integer n is given in a line.

Output

Print the given integer n and :. Then, print prime factors in ascending order. If n is divisible by a prime factor several times, the prime factor should be printed according to the number of times. Print a space before each prime factor.

Constraints

2 ≤ n ≤ 109

Sample Input 1

12

Sample Output 1

12: 2 2 3

Sample Input 2

126

Sample Output 2

126: 2 3 3 7

Solution in Scala (judge verdict: Accepted)

import scala.io.StdIn.readInt
import scala.collection.mutable.ArrayBuffer

object Main {

  def factorize(p:Int,d:Int,l:List[Int]):List[Int] = {
    if(d >= Math.sqrt(p)+1) {
      if(p != 1) p::l else l
    } else {
      if(p%d == 0)
        factorize(p/d,d,d::l)
      else if(d==2)
        factorize(p,d+1,l)
      else
        factorize(p,d+2,l)
    }
  }

  def printList(l:List[Int]):Unit = l match {
    case List() => ()
    case h::tail =>
        printList(tail)
        print(" " + h)
  }

  def main(args: Array[String]) = {
    val n = readInt
    val list = factorize(n,2,List())
    print(n.toString + ":")
    printList(list)
    println()
  }
}