Home > scala > Scala: Project Euler: Problem 3

Scala: Project Euler: Problem 3

November 22nd, 2009

Problem:

Find the largest prime factor of a composite number.

def main(args : Array[String]) : Unit = {
    println(maxPrimeFactor(BigInt("600851475143")))
  }

  def maxPrimeFactor(number:BigInt) : BigInt = {
    var max = BigInt(1)
    var lowDivisor = BigInt(1)
    var highDivisor = number
    while(highDivisor >= lowDivisor) {
      if(number % highDivisor == 0)
        if(highDivisor.isProbablePrime(10)) return maxBigInt(max, highDivisor)
        else if(lowDivisor.isProbablePrime(10)) max = maxBigInt(max, lowDivisor)
      lowDivisor += 1
      highDivisor = number/lowDivisor
    }
    if(max > 1) max else number
  }  

  def maxBigInt(x:BigInt, y:BigInt) = if(x > y) x else y

scala

  1. No comments yet.
  1. No trackbacks yet.