Skip to content

Instantly share code, notes, and snippets.

@maasg
Last active December 18, 2015 23:39
Show Gist options
  • Save maasg/5862739 to your computer and use it in GitHub Desktop.
Save maasg/5862739 to your computer and use it in GitHub Desktop.
Scala solution to TopCoder problem 'PrimeStatistics': #LearningScala
object PrimeStatistics {
def isPrime(x:Int):Boolean = {
if (x==1 || x==2 || x==3) return true
if (x % 2 == 0) return false
(3 to math.sqrt(x).toInt by 2).forall(y=>x % y != 0)
} //> isPrime: (x: Int)Boolean
def mostCommonRemainder(lowerBound:Int, upperBound:Int, modulo:Int):Int = {
val primesInRange = (lowerBound to upperBound).filter(isPrime)
val modulos = primesInRange.map(x => x % modulo)
val modFrequency = modulos.groupBy(x=>x).map({case (elem,listElem) => (elem, listElem.size)})
val maxOccurrence = modFrequency.values.max
val candidates = modFrequency.filter({case (k,v) => v==maxOccurrence})
candidates.keys.min
} //> mostCommonRemainder: (lowerBound: Int, upperBound: Int, modulo: Int)Int
mostCommonRemainder(1,1000,6) //> res1: Int = 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment