Skip to content

Instantly share code, notes, and snippets.

@stingh711
Created August 22, 2012 03:09
Show Gist options
  • Select an option

  • Save stingh711/3421953 to your computer and use it in GitHub Desktop.

Select an option

Save stingh711/3421953 to your computer and use it in GitHub Desktop.
Project euler problem 3 solution
import java.lang.Math
object Issue3 {
def isPrime(n: Long) = {
if (n <= 1) false
else if (n == 2) true
else if (n % 2 == 0) false
else {
val max = Math.sqrt(n).toInt
!3.to(max, 2).exists(n % _ == 0)
}
}
def maxFactorOf(n: Long): Long = {
val max = Math.sqrt(n).toInt
val factor = max.to(2, -1).collectFirst {case i: Int if n % i == 0 && isPrime(i) => i}
if (factor == None) n else factor.get
}
def main(args: Array[String]) {
assert(6857 == maxFactorOf(600851475143L))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment