Skip to content

Instantly share code, notes, and snippets.

@fairjm
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fairjm/f3dd9c62831ec0ff7765 to your computer and use it in GitHub Desktop.
Save fairjm/f3dd9c62831ec0ff7765 to your computer and use it in GitHub Desktop.
projecteuler_problem
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.HashMap
import scala.annotation.tailrec
/*
** author fairjm
** https://projecteuler.net/problem=5
*/
object P5 {
def getPrimesLEQ(num:Int):List[Int] = {
val buffer = ListBuffer.empty[Int]
for( i <- 2 to num ){
if((2 until i).toList.forall(i % _ != 0)) buffer += i
}
buffer.toList
}
def allFactors(num:Int)(implicit fac:List[Int]):Map[Int,Int] = {
@tailrec
def factors(last:Int,fs:List[Int],allFs:List[Int]):List[Int] = {
if(last == 1) fs
else {
allFs match {
case Nil => fs
case head::tail if last % head == 0 =>
factors(last / head,head::fs,allFs)
case head::tail =>
factors(last,fs,tail)
}
}
}
factors(num,List.empty[Int],fac).groupBy(num => num).mapValues(_.size)
}
def main(args: Array[String]): Unit = {
implicit val primes = getPrimesLEQ(10)
val map = new HashMap[Int,Int]
for(i <- 1 to 10 ){
allFactors(i).map( t => if(map.getOrElse(t._1, 0) < t._2) map.update(t._1, t._2))
}
println(map) // Map(2 -> 3, 5 -> 1, 7 -> 1, 3 -> 2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment