📜  程序打印前n个斐波纳契数|套装1

📅  最后修改于: 2021-04-29 15:25:01             🧑  作者: Mango

以下是一个简单的程序,用于打印前n个斐波那契数。

斐波那契序列

例子 :

Input : n = 3
Output : 0 1 1

Input : n = 7
Output : 0 1 1 2 3 5 8
C++
// C++ program to print
// first n Fibonacci numbers
#include 
using namespace std;
 
// Function to print
// first n Fibonacci Numbers
void printFibonacciNumbers(int n)
{
    int f1 = 0, f2 = 1, i;
 
    if (n < 1)
        return;
    cout << f1 << " ";
    for (i = 1; i < n; i++) {
        cout << f2 << " ";
        int next = f1 + f2;
        f1 = f2;
        f2 = next;
    }
}
 
// Driver Code
int main()
{
    printFibonacciNumbers(7);
    return 0;
}
 
// This code is contributed by rathbhupendra


C
// C program to print
// first n Fibonacci numbers
#include 
 
// Function to print
// first n Fibonacci Numbers
void printFibonacciNumbers(int n)
{
    int f1 = 0, f2 = 1, i;
 
    if (n < 1)
        return;
    printf("%d ", f1);
    for (i = 1; i < n; i++) {
        printf("%d ", f2);
        int next = f1 + f2;
        f1 = f2;
        f2 = next;
    }
}
 
// Driver Code
int main()
{
    printFibonacciNumbers(7);
    return 0;
}


Java
// Java program to print
// first n Fibonacci Numbers
 
class Test {
    // Method to print
    // first n Fibonacci Numbers
    static void printFibonacciNumbers(int n)
    {
        int f1 = 0, f2 = 1, i;
 
        if (n < 1)
            return;
        System.out.print(f1 + " ");
        for (i = 1; i < n; i++)
        {
            System.out.print(f2 + " ");
            int next = f1 + f2;
            f1 = f2;
            f2 = next;
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        printFibonacciNumbers(7);
    }
}


Python3
# Python program to print first n
# Fibonacci numbers
 
# Function to print first n
# Fibonacci Numbers
 
 
def printFibonacciNumbers(n):
 
    f1 = 0
    f2 = 1
    if (n < 1):
        return
    print(f1, end=" ")
    for x in range(1, n):
        print(f2, end=" ")
        next = f1 + f2
        f1 = f2
        f2 = next
 
 
# Driven code
printFibonacciNumbers(7)
 
# This code is contributed by Danish Raza


C#
// C# program to print
// first n Fibonacci Numbers
using System;
 
class Test {
    // Method to print
    // first n Fibonacci Numbers
    static void printFibonacciNumbers(int n)
    {
        int f1 = 0, f2 = 1, i;
 
        if (n < 1)
            return;
        Console.Write(f1 + " ");
        for (i = 1; i < n; i++) {
            Console.Write(f2 + " ");
            int next = f1 + f2;
            f1 = f2;
            f2 = next;
        }
    }
 
    // Driver Code
    public static void Main()
    {
         printFibonacciNumbers(7);
    }
}
 
// This code is contributed by nitin mittal.


PHP


Javascript


输出
0 1 1 2 3 5 8 

时间复杂度: O(n)