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/
파보나치 수열 중 짝수이면서 4백만 이하인 모든 항을 더하는 문제입니다.
쉬운 문제이지만 memoization 으로 시간 복잡도를 줄여봤습니다.
my solving
c++
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 | #include <iostream> #include <map> #include <ctime> using namespace std; const int limit = 4000000; map<int, int> cache; int recursive(int num) { map<int, int>::iterator it = cache.find(num); if (it != cache.end()) return it->second; int ret = 0; if (num == 0) ret = 0; else if (num == 1) ret = 1; else ret = recursive(num - 1) + recursive(num - 2); cache.insert(make_pair(num, ret)); return ret; } int main() { int ret = 0; int num = 0; int i = 0; while (true) { num = recursive(i); if (num > limit) break; if (num % 2 == 0) ret += num; i++; } cout << ret << endl; system("pause"); return 0; } | cs |
'Algorithm, Data structure > Solved Algorithmic Problem' 카테고리의 다른 글
Project Euler #5 - Smallest multiple (0) | 2016.06.11 |
---|---|
Project Euler #3 - Largest prime factor (0) | 2016.06.11 |
USACO 1.3 - Prime Cryptarithm (0) | 2016.06.11 |
USACO 1.3 - Barn Repair (0) | 2016.06.09 |
USACO 1.3 - Mixing Milk (0) | 2016.06.09 |