Skip to content

Instantly share code, notes, and snippets.

/solution.scala
Created Apr 8, 2013

Embed
What would you like to do?
Solve 10 problems of eulerproject using 20 lines scala code
import collection._
import Stream._
implicit class D(n: Int) {
def fs = (1 until n) filter (n%_ == 0) sum // sum of n's proper divisors
}
val r = mutable.Map[Int, Any]() // to store the result
val num = from(0) //all non-negative integer numbers
def isprime(n: Int) = BigInt(n) isProbablePrime 10
def len(a: Int, b: Int) = num takeWhile (x => isprime(x*x+a*x+b)) size //for 27th problem
val s22 = io.Source.fromURL("http://projecteuler.net/project/names.txt").mkString
val an = (1 to 28123) filter (x => x.fs > x) toSet //abundant numbers up to 28123
val fib: Stream[BigInt] = 0 #:: fib.scanLeft(1:BigInt)(_+_) //Fibonacci sequence
r(20) = (BigInt(1) to 100).product.toString.map(_-'0').sum
r(21) = (for(x <- 1 until 10000; f = x.fs; if f != x && f.fs == x) yield x).sum
r(22) = (s22 split "\"(,\")?" sorted, num).zipped map (_.map(_-'A'+1).sum * _) sum
r(23) = 1 to 28123 filterNot (n => 1 to n exists (x => an(x) && an(n-x))) sum
r(24) = "0123456789".permutations drop 999999 next
r(25) = fib indexWhere (_.toString.size == 1000)
r(26) = 2 to 1000 filterNot (x => x%2*x%5 == 0) maxBy (x => iterate(10:BigInt)(_*10) indexWhere (_%x == 1))
r(27) = (-999 to 999 flatMap (a => 0 to 999 map (b => (len(a,b), a*b))) max)._2
r(28) = (3 to 1001 by 2 map (x => 4*x*x-6*x+6) sum) + 1
r(29) = (BigInt(2) to 100 flatMap (x => 2 to 100 map x.pow) toSet).size
for(k <- r.keys.toSeq.sorted) println(s"[$k]: ${r(k)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.