## Intuit Interview Question

Software Engineer / Developerspackage com.badal.careercup;

import java.util.ArrayList;

public class Fibonacci {

private ArrayList<Integer> generateFibonacci (int n){

ArrayList<Integer> fib=new ArrayList<Integer>();

fib.add(0);

fib.add(1);

for(int i=2;i<n;i++){

fib.add(fib.get(i-1)+fib.get(i-2));

}

return fib;

}

public static void main(String[] args){

Fibonacci f=new Fibonacci();

System.out.println(f.generateFibonacci(13));

}

}

I take that back, badal. I do apologize. You code is not recursive, and it does help show a dynamic programming kind of approach (but not really dynamic programming).

I am the one who should follow my own advice...

And here is a dynamic programming kind of approach.

(In C# like code)

```
public static Fibonacci {
private static Dictionary<long, long> _fibonacci;
static Fibonacci() {
_fibonacci = new Dictionary<long, long>();
_fibonacci[0] = 0;
_fibonacci[1] = 1;
}
// Gets the n'th fibonacci number.
public static long Get(long n) {
if (n <= 0} {
throw new InvalidArgumentException("-ve");
}
long value;
if (_fibonacci.TryGetvalue(n, out value)) {
return value;
}
return Get(n-1) + Get(n-2);
}
}
```

int Fibonacci(int f)

{

int n = 1;

int nminus = 0;

for (int i = 0; i <= f - 2; i++)

{

int nhold = nminus;

nminus = n;

n = n + nhold;

}

return n;

}

Recursion is nice and all but will quickly bog down with large f numbers...

for the sequence simply change the return type and do a list...

IEnumerable<int> Fib(int f)

{

int n = 1;

int nminus = 0;

for (int i = 0; i <= f - 2; i++)

{

int nhold = nminus;

nminus = n;

n = n + nhold;

yield return n;

}

}

Fibonacci series is based on the distribution of chloroplasts. When they divide, they are of opposite charge. The same in java can be done as below. The benefit of the following code is that it doesnt require additional sysouts.

```
class Fibo {
public static void main(String[] args) {
int a = -1, b = 1, c = 0;
for(int count=0; count < 10; count++) {
c = a + b;
System.out.println(c);
a = b;
b = c;
}
}
}
```

Matrix m = new Matrix(new row(1,1), new row(1,0));

- Anonymous December 27, 2008Matrix FibN = m.power(n);

return FibN.Row(1).Column(1)

// Assume some implementation of Matrix...

// m = [1 1]

// [1 0]

//