Loading ...

C#: Find Fibonacci Series | CodeAsp.Net

C#: Find Fibonacci Series

 /5
0 (0votes)

What is Fibonacci series?

Sequence is set of objects (numbers) which are in Orders. Fibonacci series is a sequence of list of numbers which is invented by Leonardo Fibonacci (fi-bo-na-chee) in 1202; on the name of Leonardo Fibonacci it is named “Fibonacci series”.
Fibonacci series are:

0,1,1,2,3,5,8,13,21,34,55………

In Fibonacci series first two numbers are 0 and 1 after that each subsequent number is the sum of previous two numbers i.e.

f0=0, f1=1 now f2 will be sum of f0 and f1 and f3 will be sum of f1 and f2 like:

f2=f0+f1, f3=f2+f1 

fn=fn-1+fn-2

Seed values of the f0=0 and f1=1.

Here I have tried to generate the Fibonacci series through the C# code. We can do this as follows:

public void FibonacciSeries(int 10)
{
int f0 = 0;
int f1 = 1;
for (int i = 0; i < 10; i++)
{
//First assign the initial value to the fn.
int fn = f0;
//Print the fn value
Response.Write(fn + ", ");
//calculate fn for the next step
fn = f0 + f1;
//now f0 become f1 and f1 become fn
f0 = f1;
f1 = fn;
}
}
This will return first 10 Fibonacci series term.

OUTPUT:
0,1,1,2,3,5,8,13,21,34

In a Fibonacci series a number is a Fibonacci number if that number follows the following condition:
5fn^2 + 4  OR  5fn^2 - 4
is a perfect square, here fn is the positive integer number. I.e. fn is a Fibonacci number IFF one of 5fn^2 + 4 OR 5fn^2 - 4 is perfect square.
A perfect square is a number that has a whole number as its square root. (I.e. X^2 is equal to X times X)
To check the number (X) is perfect square or not first we calculate the square root of the number (Y) after that we calculate the square of the square root value (Y) if Square of Y is equal to the X then number(X) is a perfect square.

public void IsFibonacciNumber(int number)
{
//by the rule first we calculate 5fn^2 + 4 and 5fn^2 - 4
double f1 = 5 * Math.Pow(number, 2) + 4;
double f2 = 5 * Math.Pow(number, 2) - 4;
/*now we check one of in f1 or f2 is perfect Square root or not*/

//find out the SquareRoot of the f1
var sqrtF1 = (long)Math.Sqrt(f1);
//find out the SquareRoot of the f2
var sqrtF2 = (long)Math.Sqrt(f2);
//find out the square of the sqrtF1
var squareF1 = Math.Pow(sqrtF1, 2);
//find out the square of the sqrtF2
var squareF2 = Math.Pow(sqrtF2, 2);
bool isFibonacci = (squareF1 == f1) || (squareF2 == f2);
if (isFibonacci)
Response.Write("The given number is a Fibonacci Number");
else
Response.Write("The given numbernot a Fibonacci Number");
}
We can test this in C# as follows: 
When we check the number 5 is Fibonacci number or not.

IsFibonacciNumber(5)
OUTPUT:
The Given number 5 is a Fibonacci Number.

IsFibonacciNumber(14)
OUTPUT:
The Given number 14 is not a Fibonacci Number.


Thanks

Vijendra Singh

Comments (1)

   
joi
joi
when i compile this syntax there would be ) expected? what is wrong?
2/20/2011
 · 
by
  • :*
  • :*
  • :
 *

Top Posts