Output the nth element of the Fibonacci sequence using a recursive and non-recursive method (C language Implementation)

Source: Internet
Author: User

Faipot Series (Italian: Successione di Fibonacci), also translated into Faipot , Fibonacci series , Fermi series , the Golden section of the series .

Mathematically, the faipot sequence is defined in a recursive way:

  • {\displaystyle f_{0}=0}
  • {\displaystyle F_{1}=1}
  • {\displaystyle f_{n}=f_{n-1}+f_{n-2}} (N≧2)

In words, the faipot sequence starts with 0 and 1, and then the Fibonacci coefficients are summed up by the previous two numbers. The first few fee Fibonacci coefficients are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ... (Oeis in the series A000045)

In particular , 0 is not the first, but the 0th.

1#include <stdio.h>2 3 intFIB1 (intn);//non-recursive generation of Fibonacci sequence elements labeled N4 intFIB2 (intn);//recursive generation of Fibonacci sequence elements labeled N5 6 intMain ()7 {8     intN;9printf ("Please input the index of FIB:") ;Tenscanf ("%d", &n); Oneprintf ("The %d fib1 number is%d \ n", N, FIB1 (n)); Aprintf ("The %d fib2 number is%d \ n", N, FIB2 (n)); -     return 0 ; - } the  - intFIB1 (intN) - { -     inti =0 ; +     intA =1 ; -     intb =1 ; +     intresult =0 ; A     if(N <=0) at     { -         return 0 ; -     } -     Else if(N <=2) -     { -         return 1 ; in     } -     Else to     { +          for(i =3; I <= N; i + +) -         { theresult = A +b; *A =b; $b =result;Panax Notoginseng         } -         returnresult; the     } + } A  the intFIB2 (intN) + { -     if(N <=0) $     { $         return 0 ; -     } -     Else if(N <=2) the     { -         return 1;//recursive termination conditionsWuyi     } the     Else -     { Wu         returnFIB2 (n1) + FIB2 (n2) ;//Recursive -     } About}

Output the nth element of the Fibonacci sequence using a recursive and non-recursive method (C language Implementation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.