Fibonacci

The Fibonacci sequence is defined as follows. If Fib(k) denotes the kth number in the Fibonacci sequence, then, for non-negative positions in the sequence,

Fib(1) = 1

Fib(2) = 1

Fib(n) = Fib(n-1) + Fib(n-2)

In English, we may say that a Fibonacci number is ***** sum of its two immediate predecessors, except for the first two Fibonacci numbers, which are both 1.

Implement a class called Fibonacci. This class should provide a single class method (static) with the following signature:

double Fibonacci::getNthFibonacciRecursively(int n)

which should do exactly that. It calculates and returns the nth Fibonacci number and does so recursively, by invoking itself for certain input values of n. Note that its parameter n is an integer, but its return value is a double. Why? Answer this question in a single short sentence within the header comment of this method.

From your main(), issue calls to Fibonacci for various values of n in the range 1 to 10 and make sure that the output concurs with your paper-and-pencil calculation. Handle the case for n <= 0 by returning an invalid value and note it in the documentation of the function (within comments). For example you’d say that the function will return -1 for n <= 0. That’s perfectly acceptable.

×
New Download