Project Euler: Problem 12

Scala で超素直に書いてみた、が、止まらない。ドンマイ。Iterator - うなの日記を参考に Scalaイテレータを使ってみた。

object Problem12 {
  def divisors(n:Int) : Int = {
    var c = 1
    var result = 0
    while ( c <= n/2 ) {
      if ( n % c == 0 )
	result += 1
      c += 1
    }
    result += 1		// the given number itself is divisor
    return result
  }
  def triangles = new Iterator[Int] {
    var c = 1
    var current = 0
    def hasNext : Boolean = true
    def next : Int = {
      current += c
      c += 1
      current
    }
  }
  def main(args:Array[String]) : Unit = {
    val x : Iterator[(Boolean, Int)] =
      triangles.map((n:Int) => (divisors(n) >= 500, n))
    for ( (b, n) <- x ) {
      if ( b ) {
	println("result: "+n)
	return ()
      }
      // check current status
      if ( n % 100 == 0)
	println("now: "+n+"  divisors: "+divisors(n))
    }
  }
}

あ、止まった。

scala Problem12  1267.81s user 2.52s system 99% cpu 21:16.37 total