Fibonacci Numbers

From ScriptsPedia

Jump to: navigation, search

The Fibonacci numbers are a sequence of numbers named after Leonardo of Pisa, known as Fibonacci. Fibonacci's 1202 book Liber Abaci introduced the sequence to Western European mathematics, although the sequence had been previously described in Indian mathematics. The first number of the sequence is 0, the second number is 1, and each subsequent number is equal to the sum of the previous two numbers of the sequence itself. In mathematical terms, it is defined by the following recurrence relation:

image:fibonnaci-equation.png

C++

This code will return pairs of the fibonacci sequence, using a loop. written by talshk.

#include <iostream> //import I/O library
 
using namespace std;
 
void print_fibonacci (int n);
 
main(int argc, char *argv[])
{
 int n=0;
 while (n<1)
 {
  cout << "Enter a positive integer:\n";
  cin >> n;
 }
 cout << "Fibonacci sequence until "<< n << ":\n";
 print_fibonacci (n);
 system("PAUSE");
}
 
void print_fibonacci (int n=1)
{
 int i,j;
 for (i=1, j=n; i<j; ++i, --j)                     
     cout << "(" << i << "," <<j << ") ";
}

PHP

This code will print all the numbers in the Fibonacci sequence until n (100). written by talshk

<?php
 $n = 100;
 $a = 0;
 $b = 1;
 echo "$a, $b";
 for($i = 2; $i < $n; $i++)
 {
    $tmp = $a;
    $a = $b;
    $b = $tmp + $b;
    echo ", $b";
  }
?>

JavaScript

Javascript implementation for the Fibonacci's sequense, written by talshk.

function fibonacci(n) 
{
 var a = 1;
 var b = 1;
 var temp;
 while (--n >= 0)
 {
  temp = a;
  a += b;
  b = temp;
 }
 return a;
}
Personal tools