打印前 n 个斐波那契数

原文:

给定一个数字 n,任务是打印前 n 个。 先决条件:

示例:

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】]/【2】*

下面是实现。

c

// c   code to print fibonacci
// numbers till n using direct formula.
#include
using namespace std;
// function to calculate fibonacci
// using recurrence relation formula
void fibonacci(int n){
    long long int fib;
    for ( long long int i = 0; i < n; i  )
    {
        // using direct formula
        fib = (pow((1   sqrt(5)), i) -
               pow((1 - sqrt(5)), i)) /
              (pow(2, i) * sqrt(5));
        cout << fib << " ";
    }
}
// driver code
int main()
{
    long long int n = 8;   
    fibonacci(n);   
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// java code to print fibonacci
// numbers till n using direct formula.
class gfg{
// function to calculate fibonacci
// using recurrence relation formula
static void fibonacci(double n){
    double fib;
    for (double i = 0; i < n; i  )
    {
        // using direct formula
        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 " ");
    }
}
// driver code
public static void main(string[] args)
{
    double n = 8;
    fibonacci(n);
}
}
// this code is contributed by mits

python 3

# python3 code to print fibonacci
# numbers till n using direct formula.
import math
# function to calculate fibonacci
# using recurrence relation formula
def fibonacci(n):
    for i in range(n):
        # using direct formula
        fib = ((pow((1   math.sqrt(5)), i) -
                pow((1 - math.sqrt(5)), i)) /
               (pow(2, i) * math.sqrt(5)));
        print(int(fib), end = " ");
# driver code
n = 8;
fibonacci(n);
# this code is contributed by mits

c

// c#  code to print fibonacci
// numbers till n using direct formula.\
using system;
public class gfg{
// function to calculate fibonacci
// using recurrence relation formula
static void fibonacci(double n){
    double fib;
    for (double i = 0; i < n; i  )
    {
        // using direct formula
        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 " ");
    }
}
// driver code
    static public void main (){
            double n = 8;
            fibonacci(n);
}
}
// this code is contributed by ajit.

服务器端编程语言(professional hypertext preprocessor 的缩写)


java 描述语言


output: 

0 1 1 2 3 5 8 13

注意:上述程序与 相比成本较高,因为它会导致浮点运算。此外,由于浮点精度错误,它可能无法完美工作。