Problem 002 : Even Fibonacci numbers (5%)

link

Description

original

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.

간략해석

4,000,000이하의 피보나치 수 중 짝수의 합을 구하시오.

Idea & Algorithm

naive idea

피보나치 수열의 증가속도는 꽤나 빠르기 때문에 그냥 반복문으로 진행하면 된다. 또한 증가 수열이므로 4,000,000번 이하의 연산만 진행하면 되니 시간도 충분하다.

advanced idea

추가적으로 할 수 있는 생각이 있다면 짝수는 3으로 나눈 나머지가 2일때 나오므로 for loop에서 더 쉽게 할 수 있다.

source code

#include <stdio.h>

int main(){
    long long st = 1, snd = 2;
    long long tot = 0;
    while(snd<4000000){
        if(snd%2==0) tot += snd;
        long long tmp = snd;
        snd = st + snd;
        st = tmp;
    }
    printf("%lld",tot);
}

Leave a Comment