Another great job interview question. Get somebody to write a function that will generate a list of fibonacci numbers and calculate the sum of the values that do not exceed four million.

In case you are not aware the fibonacci sequence is generated by adding the previous two terms of the sequence. So a basic sequence of the numbers looks like. 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ...

static void Main(string[] args) { DateTime Start = DateTime.Now; UInt64 Total = 0; UInt64 Fib = 1; UInt64 Last = 0; do { UInt64 tmp = Fib; Fib = Fib + Last; Last = tmp; Console.WriteLine(Fib); if (Fib % 2 == 0 && Fib <= 4000000) Total += Fib; } while (Fib <= 4000000); Console.WriteLine("Answer: {0}", Total); Console.WriteLine("Time Taken: {0}", DateTime.Now - Start); Console.ReadLine(); }

Something that an interviewed should not do here is ask you to do something with the sequence and not provide you with enough information to generate the sequence. If they do you should probably come back with a question of. do you expect your employee's to know all mathmatical sequences of numbers?

11/6/2011 7:55:30 AM #

Great solution but with a little problem.

if (Fib % 2 == 0 && Fib <= 4000000)

Total += Fib;

The calculation itself is wrong

araven666 |

11/6/2011 8:16:09 AM #

I suggest you check again!

james |