#!/usr/bin/scala
!#
{
println((0 to 999 toList).filter(s => (s%3==0 || s%5==0)).foldLeft(0)((a,b)=>a+b))
}
{
def f(x:Int,y:Int,s:Int):Int =
if (x <= 4000000) f(y,x+y,x*(1-x%2) + s) else s
println(f(1,2,0))
}
{
def f(n:Long,x:Long):Long =
if(n<=x) x else
if(n%x==0) f(n/x,x) else f(n,x+1)
println(f(600851475143L,2))
}
{
println((0 to 999999).reverse.find(
i=>i.toString == i.toString.reverse.toString &&
(100 to 999).exists(
j=>i%j==0 && i/j>=100 && i/j<=999
)
).getOrElse(0))
}
{
def gcd(x : Long, y : Long) : Long =
if (y==0) x else gcd(y,x%y)
println((1 to 20).foldLeft(1L)((i,j) => i/gcd(i,j)*j))
}
{
def sum(x : List[Int]) : Int =
x.foldLeft(0)((i,j) => i+j)
def sq(x : Int) : Int = x*x
val l = 1 to 100
println(sq(sum(l toList)) - sum(l.map(sq) toList))
}
{
var cnt = 0
var siv = new Array[Boolean](110000)
for(i <- 2 until 110000) {
if(!siv(i)) {
for(j <- i until 110000 by i) {
siv(j) = true
}
cnt += 1
if(cnt == 10001) {
println(i)
}
}
}
}
{
val data =
"73167176531330624919225119674426574742355349194934" +
"96983520312774506326239578318016984801869478851843" +
"85861560789112949495459501737958331952853208805511" +
"12540698747158523863050715693290963295227443043557" +
"66896648950445244523161731856403098711121722383113" +
"62229893423380308135336276614282806444486645238749" +
"30358907296290491560440772390713810515859307960866" +
"70172427121883998797908792274921901699720888093776" +
"65727333001053367881220235421809751254540594752243" +
"52584907711670556013604839586446706324415722155397" +
"53697817977846174064955149290862569321978468622482" +
"83972241375657056057490261407972968652414535100474" +
"82166370484403199890008895243450658541227588666881" +
"16427171479924442928230863465674813919123162824586" +
"17866458359124566529476545682848912883142607690042" +
"24219022671055626321111109370544217506941658960408" +
"07198403850962455444362981230987879927244284909188" +
"84580156166097919133875499200524063689912560717606" +
"05886116467109405077541002256983155200055935729725" +
"71636269561882670428252483600823257530420752963450";
val numlist = data.map[Int](ch => ch-'0') toArray;
println((0 to numlist.length-5).map(
i => numlist.slice(i,i+5).foldLeft(1)((i,j) => i*j)).
foldLeft(0)((i,j) => i max j))
}
{
// self-evidently 8, 15, 17
val mult = 1000 / (8+15+17)
val prod = 8*15*17*mult*mult*mult
println(prod)
}
{
//def sieve(x:Stream[Int]):Stream[Int] = Stream.cons(x.head,
// sieve(x.tail.filter(i => i%x.head!=0)))
//lazy val primes = sieve(Stream.from(2))
def sieve(s:Int) : Stream[Int] = {
var siever = new Array[Boolean](s*2)
for(p <- primes.takeWhile(i=>i*i<s*2)) {
for(i <- (p*p until s*2 by p)) {
siever(i) = true
}
}
def sieve_inner(i:Int) : Stream[Int] =
if(i==s*2) sieve(i)
else if(siever(i)) sieve_inner(i+1)
else Stream.cons(i,sieve_inner(i+1))
return sieve_inner(s)
}
lazy val primes = Stream.cons(2,Stream.cons(3,sieve(4)))
println(primes.takeWhile(i=>i<2000000).foldLeft(0L)((i,j)=>i+j))
}