Created
August 29, 2015 09:21
-
-
Save kikitux/2859b03fd1ff7b9d745d to your computer and use it in GitHub Desktop.
Fibonacci C++ Using Vector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://www.cs.utexas.edu/users/EWD/transcriptions/EWD06xx/EWD654.html | |
// http://www.cs.utexas.edu/users/EWD/ewd06xx/EWD654.PDF | |
// F(2n) = (2*F(n-1) + F(n) )*F(n) | |
// F(2n-1) = F(n-1)^2 + F(n)^2 | |
unsigned long intfibdijkstra(unsigned long n) { | |
static std::vector<unsigned long> values = {0,1,1}; | |
if (n == 0 ) { | |
return values[n]; | |
} | |
if (n < values.size() && values[n] != 0 ) { | |
return values[n]; | |
} | |
if (values.capacity() < n){ | |
values.reserve(n); | |
} | |
if (values.size() < n){ | |
values.resize(n); | |
} | |
if (n%2==0){ | |
unsigned long num = n/2; | |
if (values[num-1]==0) | |
values.at(num-1)=intfibdijkstra(num-1); | |
if (values[num]==0) | |
values.at(num)=intfibdijkstra(num); | |
return (2*values[num-1]+values[num])*values[num]; | |
} | |
else { | |
unsigned long num = (n+1)/2; | |
if (values[num-1]==0) | |
values.at(num-1)=intfibdijkstra(num-1); | |
if (values[num]==0) | |
values.at(num)=intfibdijkstra(num); | |
return values[num-1]*values[num-1]+values[num]*values[num]; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
unsigned long intfibonacci(unsigned long n) { | |
static std::vector<unsigned long> values = {0,1,1}; | |
if (n < values.size() ) { | |
return values[n]; | |
} | |
for (unsigned long loop = values.size(); loop-1 < n ; ++loop){ | |
values.push_back(values[loop-2] + values[loop-1]); | |
} | |
return values[n]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment