I am working on this assignment and i trying to figure this out. When i input any other numbers between 1 to 10 except 6. The fibonacci_fast(n) outputs an error main: malloc.c:2401: sysmalloc: Assertion. However, when i use an array to replace the vector or just uncomment the std::cout. It will work fine. Can anyone enlighten me what's the error that i have made.
#include <iostream>
#include <cassert>
#include <vector>
#include <algorithm>
int fibonacci_naive(int n) {
if (n <= 1)
return n;
return fibonacci_naive(n - 1) + fibonacci_naive(n - 2);
}
int fibonacci_fast(int n) {
std::vector<int> numbers{0,n};
numbers[0] =0;
numbers[1] =1;
int ans=0;
if (n <= 1)
{
return n;
}
//std::cout<<std::endl;
//int numbers[n];
for(int i=2;i<=n;i++)
{
numbers[i] = numbers[i-1] + numbers[i-2];
}
ans = numbers[n];
return ans;
}
void test_solution() {
assert(fibonacci_fast(3) == 2);
assert(fibonacci_fast(10) == 55);
for (int n = 0; n < 20; ++n)
assert(fibonacci_fast(n) == fibonacci_naive(n));
}
int main() {
int n = 0;
std::cin >> n;
//std::cout << fibonacci_naive(n) << '\n';
//test_solution();
std::cout << fibonacci_fast(n) << std::endl;
return 0;
}