Created
August 22, 2012 03:09
-
-
Save stingh711/3421953 to your computer and use it in GitHub Desktop.
Project euler problem 3 solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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