import kotlin.system.measureNanoTime

/**
 * Even Fibonacci numbers
 *
 * Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the
 * first 10 terms will be:
 *
 *                                  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
 *
 * By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the
 * even-valued terms.
 *
 * https://projecteuler.net/problem=2
 */
fun main() {
    val limit = 4_000_000
    val solution1Time = measureNanoTime {
        solution1(limit)
    }
    val solution2Time = measureNanoTime {
        solution2(limit)
    }

    println(solution1Time)
    println(solution2Time)
}

private fun solution1(limit: Int) {
    var n1 = 1
    var n2 = 1
    var sum = 0

    while (n2 < limit) {
        if (n2 % 2 == 0) {
            sum += n2
        }
        val fib = n1 + n2
        n1 = n2
        n2 = fib
    }
    println(sum)
}

private fun solution2(limit: Int) {
    // 1 1 2 3 5 8 13 21 34 55 89 144
    // a b c a b c a  b  c  a  b   c
    var a = 1
    var b = 1
    var c = a + b
    var sum = 0

    while (c < limit) {
        sum += c
        a = b + c
        b = c + a
        c = a + b
    }
    println(sum)
}
