Skip to content

Instantly share code, notes, and snippets.

@fupfin
Last active December 16, 2015 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fupfin/5479615 to your computer and use it in GitHub Desktop.
Save fupfin/5479615 to your computer and use it in GitHub Desktop.
오일러 프로젝트 문제 2: http://euler.synap.co.kr/prob_detail.php?id=2 피보나치 수열의 각 항은 바로 앞의 항 두 개를 더한 것이 됩니다. 1과 2로 시작하는 경우 이 수열은 아래와 같습니다. 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... 짝수이면서 4백만 이하인 모든 항을 더하면 얼마가 됩니까?
package com.fupfin.euler.problem2
import scala.collection.immutable.Stream._
import scala.collection.GenIterable
object Problem2 {
def fib(max: Int): Stream[Int] = 1 #:: 2 #:: fib(1, 2, max)
private def fib(v1:Int, v2:Int, max:Int): Stream[Int] = if(v1 + v2 <= max) (v1 + v2) #:: fib(v2, v1 + v2, max) else Empty
def sum(that:GenIterable[Int], p: Int => Boolean): Int = {
def loop(that: GenIterable[Int], acc: Int): Int = {
if(that.isEmpty) acc
else loop(that.tail, acc + (if (p(that.head)) that.head else 0))
}
loop(that, 0)
}
def sumOfEvenFibonacciNumbersLessThan4000000 = sum(fib(4000000), _ % 2 == 0)
}
package com.fupfin.euler.problem2
import org.scalatest.FlatSpec
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.matchers.ShouldMatchers
@RunWith(classOf[JUnitRunner])
class Problem2Spec extends FlatSpec with ShouldMatchers {
import Problem2._
"first 7 fibonacci numbers" should "be 1, 2, 3, 5, 8, 13, 21" in {
List(1, 2, 3, 5, 8, 13, 21).zip(fib(30)).forall(v => v._1 == v._2) should equal (true)
}
"sum of 1, 2, 3, 4, 5" should "be 15" in {
sum(List(1, 2, 3, 4, 5), _ => true) should equal (15)
}
"sum of fibonacci numbers" should "be 19" in {
sum(fib(10), _ => true) should equal (19)
}
"sum of even elements of fibonacci numbers" should "10" in {
sum(fib(10), _ % 2 == 0) should equal (10)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment