📜  TCS编码实践问题|斐波那契系列

📅  最后修改于: 2021-05-24 16:22:02             🧑  作者: Mango

给定数字“ n”,任务是使用命令行参数打印斐波那契数列。斐波那契数是以下整数序列中的数字。

用数学术语来说,斐波纳契数的序列Fn由递归关系定义

Fn = Fn-1 + Fn-2

具有种子值

F0 = 0 and F1 = 1.

例子:

Input: n = 3
Output: 0, 1, 1

Input: 7
Output: 0, 1, 1, 2, 3, 5, 8

方法:

  • 由于该数字是作为命令行参数输入的,因此不需要专用的输入行
  • 从命令行参数中提取输入数字
  • 提取的数字将为String类型。
  • 将此数字转换为整数类型并将其存储在变量中,例如num
  • 找到该数字的反面并存储在变量中,例如rev_num
  • 检查此rev_num和num是否相同。
  • 如果它们不相同,则数字不是回文
  • 如果相同,则为回文数

程序:

C
// C program to print the Fibonacci Series
// using command line arguments
  
#include 
#include  /* atoi */
  
// Function to print the Fibonacci Series
void fib(int n)
{
  
    int a = 0, b = 1, c, i;
  
    if (n <= 1)
        printf("%d ", a);
    else {
  
        printf("%d %d ", a, b);
  
        for (i = 3; i <= n; i++) {
            c = a + b;
            a = b;
            b = c;
  
            printf("%d ", c);
        }
  
        printf("\n");
    }
}
  
// Driver code
int main(int argc, char* argv[])
{
  
    int num, res = 0;
  
    // Check if the length of args array is 1
    if (argc == 1)
        printf("No command line arguments found.\n");
  
    else {
  
        // Get the command line argument and
        // Convert it from string type to integer type
        // using function "atoi( argument)"
        num = atoi(argv[1]);
  
        // Print the Fibonacci series
        fib(num);
    }
    return 0;
}


Java
// Java program to print the Fibonacci Series
// using command line arguments
  
class GFG {
  
    // Function to print the Fibonacci Series
    static void fib(int n)
    {
  
        int a = 0, b = 1, c, i;
  
        if (n <= 1)
            System.out.print(a + " ");
        else {
  
            System.out.print(a + " " + b + " ");
  
            for (i = 3; i <= n; i++) {
                c = a + b;
                a = b;
                b = c;
  
                System.out.print(c + " ");
            }
  
            System.out.println();
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Check if length of args array is
        // greater than 0
        if (args.length > 0) {
  
            // Get the command line argument and
            // Convert it from string type to integer type
            int num = Integer.parseInt(args[0]);
  
            // Print the Fibonacci series
            fib(num);
        }
        else
            System.out.println("No command line "
                               + "arguments found.");
    }
}


输出:

  • 在C中:

  • 在Java:

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”