Skip to content

Instantly share code, notes, and snippets.

@alexflav23
Created July 15, 2013 13:41
Show Gist options
  • Save alexflav23/6000027 to your computer and use it in GitHub Desktop.
Save alexflav23/6000027 to your computer and use it in GitHub Desktop.
ProjectEuler#14 - Longest Collatz Sequence
package org.projecteuler.exercises
import scala.annotation.tailrec;
import scala.collection.mutable.HashMap;
object LargestCollatzSeq {
val map: HashMap[BigInt, BigInt] = new HashMap
val limit = 1000000
@tailrec
def rec(x: BigInt, count: BigInt = 1, original: BigInt): BigInt = {
if (x == 1) {
map.put(original, count)
count
} else {
map.get(x) match {
case Some(data) =>
map.put(original, count + data - 1)
count + data - 1
case None => (x % 2).toInt match {
case 0 => rec(x / 2, count + 1, original)
case 1 => rec(3 * x + 1, count + 1, original)
}
}
}
}
def largestSeq = {
var max: BigInt = 0;
var number: BigInt = 0;
for (i <- 2 to limit) {
val c = rec(i, 1, i);
if (c > max) {
number = i;
max = c
}
}
println(s"$number -> $max")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment