使用递归以相反的顺序打印斐波那契数列
给定一个整数N,任务是使用递归以相反的顺序打印斐波那契数列的前N项。
例子:
Input: N = 5
Output: 3 2 1 1 0
Explanation: First five terms are – 0 1 1 2 3.
Input: N = 10
Output: 34 21 13 8 5 3 2 1 1 0
方法:这个想法是使用递归的方式,不断调用相同的函数,直到N大于0并继续添加术语,然后开始打印术语。
请按照以下步骤解决问题:
- 定义一个函数fibo(int N, int a, int b)其中
- N是术语的数量,并且
- a和b是初始项,值为0和1 。
- 如果N大于0,则使用值N-1, b, a+b再次调用该函数。
- 函数调用后,打印a作为答案。
下面是上述方法的实现。
C++
// C++ program for the above approach
#include
using namespace std;
// Function to print the fibonacci
// series in reverse order.
void fibo(int n, int a, int b)
{
if (n > 0) {
// Function call
fibo(n - 1, b, a + b);
// Print the result
cout << a << " ";
}
}
// Driver Code
int main()
{
int N = 10;
fibo(N, 0, 1);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
public class GFG
{
// Function to print the fibonacci
// series in reverse order.
static void fibo(int n, int a, int b)
{
if (n > 0) {
// Function call
fibo(n - 1, b, a + b);
// Print the result
System.out.print(a + " ");
}
}
// Driver Code
public static void main(String args[])
{
int N = 10;
fibo(N, 0, 1);
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# Python program for the above approach
# Function to print the fibonacci
# series in reverse order.
def fibo(n, a, b):
if (n > 0):
# Function call
fibo(n - 1, b, a + b)
# Print the result
print(a, end=" ")
# Driver Code
if __name__ == "__main__":
N = 10
fibo(N, 0, 1)
# This code is contributed by Samim Hossain Mondal.
C#
// C# program for the above approach
using System;
class GFG
{
// Function to print the fibonacci
// series in reverse order.
static void fibo(int n, int a, int b)
{
if (n > 0) {
// Function call
fibo(n - 1, b, a + b);
// Print the result
Console.Write(a + " ");
}
}
// Driver Code
public static void Main()
{
int N = 10;
fibo(N, 0, 1);
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
34 21 13 8 5 3 2 1 1 0
时间复杂度: O(N)
辅助空间: O(N)