Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci wrong output? (C)

int * fibonacci(int n) {
    int range = n + 1;
    int * arr = malloc(range * sizeof(int));
    arr(0) = 0;
    arr(1) = 1;
    for(int i = 2; i < range; ++i) {
        arr(i) = arr(0) + arr(1);   
    }
    return arr;
}

I can't seem to pinpoint what's wrong with my program, the output keeps coming out as 0, 1, 1, 1, 1 and so on?

like image 315
user2175838 Avatar asked Dec 27 '22 07:12

user2175838


2 Answers

arr(i) = arr(0) + arr(1);   

shouldn't that be

arr(i) = arr(i-1) + arr(i-2);

?

like image 175
user829323 Avatar answered Dec 28 '22 19:12

user829323


What your code does is the following:

arr(3) = 0 + 1
arr(4) = 0 + 1
arr(5) = 0 + 1

etc. You are assigning the same value over and over.

You need to do:

 arr(i) = arr(i - 1) + arr(i - 2);

Explanation:

Say you have the array:

  • arr(1) = 0
  • arr(2) = 1

and i is at index 3, this would assign arr(3) = arr(2) + arr(1) which is 1 + 0. Therefore arr(3) = 1

i is now at index 4, this would assign arr(4) = arr(3) + arr(2) which is 1 + 1. Therefore arr(4) = 2

like image 24
Darren Avatar answered Dec 28 '22 21:12

Darren