Skip to content

Even Fibonacci numbers

Solve on HackerRankEasy

This is a programming version of Problem 2 from projecteuler.net.

Find the fibonacci series with the last element just equal to or less then the given NN. Then sum up all the even valued terms in the series.

C++
#include <bits/stdc++.h>
using namespace std;
int main() {
int tc;
cin >> tc;
while (tc--) {
long long n;
cin >> n;
long long a = 0, b = 1, c;
long long res = 0;
while (1) {
c = a + b;
if (c > n) break;
if (c % 2 == 0) res += c;
a = b;
b = c;
}
cout << res << "\n";
}
}

Give it a try first

Attempt the problem on HackerRank — the code will still be here.