Print first n Fibonacci Numbers using direct formula
Last Updated :
23 Aug, 2022
Given a number n, the task is to print first n Fibonacci numbers.
Prerequisite: Program to print first n Fibonacci Numbers | Set 1
Examples:
Input : 7
Output :0 1 1 2 3 5 8
Input : 5
Output :0 1 1 2 3
N-th Fibonacci Number = [(1 + ?5)n – (1 – ?5)n)] / [2n * ?5]
Below is the implementation.
C++
#include<bits/stdc++.h>
using namespace std;
void fibonacci( int n){
long long int fib;
for ( long long int i = 0; i < n; i++)
{
fib = ( pow ((1 + sqrt (5)), i) -
pow ((1 - sqrt (5)), i)) /
( pow (2, i) * sqrt (5));
cout << fib << " " ;
}
}
int main()
{
long long int n = 8;
fibonacci(n);
return 0;
}
|
Java
class GFG{
static void fibonacci( double n){
double fib;
for ( double i = 0 ; i < n; i++)
{
fib = (Math.pow(( 1 + Math.sqrt( 5 )), i) -
Math.pow(( 1 - Math.sqrt( 5 )), i)) /
(Math.pow( 2 , i) * Math.sqrt( 5 ));
System.out.print(( int )fib+ " " );
}
}
public static void main(String[] args)
{
double n = 8 ;
fibonacci(n);
}
}
|
Python3
import math
def fibonacci(n):
for i in range (n):
fib = (( pow (( 1 + math.sqrt( 5 )), i) -
pow (( 1 - math.sqrt( 5 )), i)) /
( pow ( 2 , i) * math.sqrt( 5 )));
print ( int (fib), end = " " );
n = 8 ;
fibonacci(n);
|
C#
using System;
public class GFG{
static void fibonacci( double n){
double fib;
for ( double i = 0; i < n; i++)
{
fib = (Math.Pow((1 + Math.Sqrt(5)), i) -
Math.Pow((1 - Math.Sqrt(5)), i)) /
(Math.Pow(2, i) * Math.Sqrt(5));
Console.Write(( int )fib+ " " );
}
}
static public void Main (){
double n = 8;
fibonacci(n);
}
}
|
PHP
<?php
function fibonacci( $n )
{
for ( $i = 0; $i < $n ; $i ++)
{
$fib = (pow((1 + sqrt(5)), $i ) -
pow((1 - sqrt(5)), $i )) /
(pow(2, $i ) * sqrt(5));
echo $fib , " " ;
}
}
$n = 8;
fibonacci( $n );
?>
|
Javascript
<script>
function fibonacci(n)
{
var fib;
for (i = 0; i < n; i++)
{
fib = (Math.pow((1 + Math.sqrt(5)), i) -
Math.pow((1 - Math.sqrt(5)), i)) /
(Math.pow(2, i) * Math.sqrt(5));
document.write(parseInt(fib) + " " );
}
}
var n = 8;
fibonacci(n);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Note: The above program is costly compared to method 1 as it causes power computations in floating point. Also, it may not work perfectly due to floating point precision errors.
Share your thoughts in the comments
Please Login to comment...