/
Even_Fibonacci_Numbers.scala
65 lines (49 loc) · 1.65 KB
/
Even_Fibonacci_Numbers.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
Project Euler #2: Even Fibonacci Numbers
------------------------------------------
Link: https://www.hackerrank.com/contests/wissen-coding-challenge-2021/challenges/euler002
------------------------------------------
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 N, find the sum of the even-valued terms.
Input Format
First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N.
Output Format
Print the required answer for each test case.
Sample Input 0
2
10
100
Sample Output 0
10
44
Explanation 0
For N=10, we have {2,8}, sum is 10.
For N=100, we have {2,8,34}, sum is 44.
*/
(Scala Solution)
import scala.io.StdIn
import scala.collection.mutable.ArrayBuffer
object Solution {
def main(args: Array[String]) {
val num = StdIn.readLine().toInt
val input_max_val = for (i <- 1 to num) yield BigInt(StdIn.readLine)
val evenFibs = {
val evenFibs = ArrayBuffer.empty[BigInt]
var f_0:BigInt = 0
var f_1:BigInt = 1
while (f_1 < input_max_val.max) {
if (f_1 % 2 == 0) {
evenFibs += f_1
}
val f_next = f_0 + f_1
f_0 = f_1
f_1 = f_next
}
evenFibs
}
for (n <- input_max_val) {
println(evenFibs.takeWhile(_ <= n).sum)
}
}
}