Skip to content

Instantly share code, notes, and snippets.

@psfblair
Created August 22, 2010 22:19
Show Gist options
  • Select an option

  • Save psfblair/544351 to your computer and use it in GitHub Desktop.

Select an option

Save psfblair/544351 to your computer and use it in GitHub Desktop.
/* If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
*/
// List comprehension
object ex1_a {
val multiples = for (i <- List.range(1, 1000) if i % 3 == 0 || i % 5 == 0 ) yield i;
val answer = multiples.foldLeft (0) ((x,y) => x + y);
}
// Using sets
object ex1_b {
val multiplesOf3 = 0 until 1000 by 3
val multiplesOf5 = 0 until 1000 by 5
//val answer = (multiplesOf3 union multiplesOf5).foldLeft (0) ((x,y) => x + y); //Range union isn't set union
//val answer = multiplesOf3.union(multiplesOf5).foldLeft (0) ((x,y) => x + y);
val answer = new scala.collection.immutable.HashSet().++(multiplesOf3).++(multiplesOf5).foldLeft (0) ((x,y) => x + y);
}
// Lazy list
object ex1_c {
lazy val multiples = for (i <- Iterator.from(0) if i % 3 == 0 || i % 5 == 0 ) yield i;
val answer = multiples.takeWhile((x) => x < 1000).foldLeft (0) ((x,y) => x + y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment