**Problem:**

- 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.

**Algorithm:**

- As explained in the problem statement, you can compute all Fibonacci numbers in an iterative way:
`F_i=F_{i-2}+F_{i-1}`

- My variables ”a” and ”b” stand for
`F_{i-2}`

and`F_{i-1}`

whereas ”next” is`F_i`

- After each iteration, ”next=a+b” and then ”a” becomes ”b” and ”b” becomes ”next”.
- A number is even if there is no remainder when divided by 2.
- In most programming languages it’s written as ”variable % 2 == 0”
- Internally, your compiler might translate this to the more efficient ”(variable & 1) == 0”

**Note:**

- ”unsigned long long” is required to pass all Hackerrank tests.

**Program**:

.wp-block-code {
border: 0;
padding: 0;
-webkit-text-size-adjust: 100%;
text-size-adjust: 100%;
}
.wp-block-code > span {
display: block;
overflow: auto;
}
.shcb-language {
border: 0;
clip: rect(1px, 1px, 1px, 1px);
-webkit-clip-path: inset(50%);
clip-path: inset(50%);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
word-wrap: normal;
word-break: normal;
}
.hljs {
box-sizing: border-box;
}
.hljs.shcb-code-table {
display: table;
width: 100%;
}
.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}
.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}
.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
}
.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}
.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}
.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}
.hljs.shcb-line-numbers .shcb-loc > span {
padding-left: 0.75em;
}
.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
padding: 0 0.75em;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```
#include <iostream>
int main()
{
unsigned int tests;
std::cin >> tests;
while (tests--)
{
unsigned long long last;
std::cin >> last;
unsigned long long sum = 0;
// first Fibonacci numbers
unsigned long long a = 1;
unsigned long long b = 2;
// until we reach the limit
while (b <= last)
{
// even ?
if (b % 2 == 0)
sum += b;
// next Fibonacci number
auto next = a + b;
a = b;
b = next;
}
std::cout << sum << std::endl;
}
return 0;
}
```

Code language: C++ (cpp)