Created
December 13, 2011 22:50
-
-
Save giuniu/7aed55fccd60dcbb2b18 to your computer and use it in GitHub Desktop.
原始ピタゴラス数探索ロジック:Scala版
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 math._ | |
object PythagoraSwitch { | |
def main(args: Array[String]): Unit = { | |
val max = Integer.parseInt(args(0)) | |
val start = System.nanoTime() | |
/* | |
val result = for ( | |
c <- 3 to max by 2; | |
c2 = c.toLong * c; | |
b <- (c / Math.sqrt(2)).ceil.toInt until c; | |
a2 = c2 - b.toLong * b; | |
a = Math.sqrt(a2).toInt; | |
if (a2 == a.toLong * a) && (gcd(c, gcd(b, a)) == 1) | |
) yield (a, b, c) | |
*/ | |
val result = (3 to max by 2).par flatMap(c => { | |
val c2 = c.toLong * c | |
(c / sqrt(2)).ceil.toInt until c withFilter (b=> { | |
val a2 = c2 - b.toLong * b | |
val a = sqrt(a2).toInt | |
(a2 == a.toLong * a) && (gcd(c, gcd(b, a)) == 1) | |
}) map (b => { | |
val a2 = c2 - b.toLong * b | |
val a = sqrt(a2).toInt | |
(a, b, c) | |
}) | |
}) | |
val end = System.nanoTime() | |
result foreach println | |
println("count:" + result.length) | |
println("time:" + ((end - start) / 1000000)) | |
} | |
def gcd(max: Int, min: Int): Int = (max % min) match { | |
case 0 => min | |
case r => gcd(min, r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment