Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Forked from ponkotuy/Prob44_2.d
Last active December 18, 2015 13:39
Show Gist options
  • Save xuwei-k/5791413 to your computer and use it in GitHub Desktop.
Save xuwei-k/5791413 to your computer and use it in GitHub Desktop.
object Prob44_2 {
def pentagonal(n: Int) = n*(3*n - 1)/2
private[this] val pentagonals = Iterator.from(0).map(pentagonal).takeWhile(_ < (Int.MaxValue >> 2)).toArray
def isPenta(n: Int) = {
val dbl = (1.0 + math.sqrt(1 + 24*n))/6.0
val int = dbl.toInt
pentagonal(int) == n || pentagonal(int + 1) == n
}
def check(j: Int, k: Int): Boolean = {
val pj = pentagonals(j)
val pk = pentagonals(k)
isPenta(pj + pk) && isPenta((pj - pk).abs)
}
def w(){
val result = collection.mutable.ArrayBuffer[(Int, Int)]()
var i = 1
while(i <= 10000){
var j = i + 1
while(j <= 10001){
if(check(i, j)){
result += ((i, j))
}
j += 1
}
i += 1
}
println(result.head)
}
def f(){
val result = for {
i <- 1 to 10000
j <- (i + 1) to 10001
if check(i, j)
} yield (i, j)
println(result.head)
}
def time[A](f: => A): A = {
val start = System.nanoTime
val r = f
val end = System.nanoTime
println(((end - start) / 1000000))
r
}
def main(args: Array[String]) {
print("while ")
time(w())
print("for ")
time(f())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment