These are two of tasks, which I had to do for the recruitment process to be started in some company. Unfortunately they didn't like it so I've decided to share it here for discussion.
Add up all the even elements of the fibonacci sequence below 1000. In my solution it is a method: fibSumEven
Write a recursive function that calculates the fibonacci sequence up to 1000. In my solution it is a method: fibR
My solution looked like this:
Fibonacci.h
#ifndef FIBONACCI_H_
#define FIBONACCI_H_
#include <iostream>
#include <string>
#include <sstream>
class CFibonacci
{
private:
// Recursive function that calculates the Fibonacci sequence up to given LIMIT
// limit - The limit, up to which sequence numbers will be calculated
static int fibHelper(int limit, int x1, int x2)
{
int x = x1 + x2;
if(x <= limit)
{
return fibHelper(limit, x2, x);
}
return x2;
}
public:
// A caller to recursive Fibonacci sequence up to given limit
static int fibR(int limit = 1000)
{
if(limit <= 0)
{
return 0;
}
return fibHelper(limit, 0, 1);
}
//Adds up all the even elements of the Fibonacci sequence below limit
static int fibSumEven(int limit=1000)
{
int x1 = 0, x2 = 1, x = 0, sum = 0;
while(x <= limit)
{
x = x1 + x2;
if(x % 2 == 0)
{
sum += x;
}
x1 = x2;
x2 = x;
}
return sum;
}
};
#endif /* FIBONACCI_H_ */
There was a disclaimer: Considering the ith element of the Fibonacci sequence Fib(i) = x, the element x is a natural number and is itself bounded by the value 1000 and not all the elements to Fib(1000).
Why the above solution could be disliked by the recruiters?