Scalaで素因数分解

scala素因数分解を書いてみた。1つ目は従来の命令型で。
2つ目は再帰で書いてみた。

import scala.math._

object Math {
	/**
	 * 素因数分解
	 * prime decomposition; prime factor decomposition
	*/
	def calc素因数分解(n:Int):List[Int] = {
		var result = new ListBuffer[Int]()
		var 残りの数 = n
		var 割る数 = 2
		var 調べればいい上限 = sqrt(n)
		while (割る数 < 調べればいい上限) {
			if (残りの数 % 割る数 == 0) {
				result += 割る数
				残りの数 /= 割る数
				調べればいい上限 = sqrt(残りの数)
			} else {
				割る数 += 1
			}			
		}
		result += 残りの数
		result.toList
	}

        /** 再帰版 */
	def calc素因数分解2(n:Int):List[Int] = {
		def sub(start:Int, n:Int):List[Int] = {
			if (start > sqrt(n))
				List(n)
			else if (n % start == 0)
				start :: sub(start, n / start)
			else
				sub(start+1, n)
		}
		sub(2, n)
	}



	def main(args:Array[String]) {
		println("Math")
		println("素因数分解 333333331="+calc素因数分解(333333331).mkString("*"))
		println("素因数分解 33333331="+calc素因数分解(33333331).mkString("*"))
		println("素因数分解 360="+calc素因数分解(360).mkString("*"))
		println("素因数分解 333333331="+calc素因数分解2(333333331).mkString("*"))
		println("素因数分解 33333331="+calc素因数分解2(33333331).mkString("*"))
		println("素因数分解 360="+calc素因数分解2(360).mkString("*"))
	}
}