Created
February 18, 2011 23:50
-
-
Save d2fn/834627 to your computer and use it in GitHub Desktop.
bitsets, use them for everything!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import euler.Functions._ | |
import scala.math._ | |
val q = "What is the smallest positive " + | |
"number that is evenly divisible by " + | |
"all of the numbers from 1 to 20?" | |
def hasDivisors(n:Long, divisors:Seq[Long]) = { | |
divisors.filter(n%_ > 0).isEmpty | |
} | |
val divisors = 1L to 20L | |
val candidates = | |
for(i <- 1L to pow(2,20).toLong) | |
yield | |
divisors.filter{ x => | |
val mask = 1<<(x-1) | |
(mask & i) == mask | |
}.foldLeft(1L)(_*_) | |
val ans = candidates.filter(hasDivisors(_,divisors)).reduceRight(_ min _) | |
println(q + ": " + ans) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment