Created
February 3, 2013 07:21
-
-
Save zerosum/4700829 to your computer and use it in GitHub Desktop.
Project Euler: Problem 21
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
| package euler.zerosum | |
| package object Divisors { | |
| /** | |
| * 自身を除いたnの約数を返す。 | |
| * 約数は昇順にソートされる。 | |
| * | |
| * @param n | |
| * @return | |
| */ | |
| def getDivisors(n: Int): Stream[Int] = { | |
| val divs = Number.from(1).take(math.sqrt(n).toInt).filter(n%_ == 0) | |
| (divs ++ divs.map(n/_).filterNot(x => x == n || x == divs.last)).sortWith(_<_) | |
| } | |
| } | |
| package object Number { | |
| /** | |
| * n以上の整数の無限数列を生成する | |
| * | |
| * @param n | |
| * @return | |
| */ | |
| def from(n: Int):Stream[Int] = n #:: from(n + 1) | |
| } |
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
| package euler.zerosum | |
| import euler.zerosum.Divisors._ | |
| import euler.zerosum.Number._ | |
| object Euler0021 { | |
| def main(args: Array[String]) { | |
| println(from(1).take(9999).filter(hasAmicable(_)).sum) | |
| } | |
| private def hasAmicable(n: Int): Boolean = { | |
| val sumOfDivs = getDivisors(n).sum | |
| n != sumOfDivs && n == getDivisors(sumOfDivs).sum | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment