C language implements Fibonacci sequence recursion

  • 2020-07-21 09:30:25
  • OfStack


/*
 Problem description 
Fibonacci The recurrence formula of the sequence is: Fn=Fn-1+Fn-2 , including F1=F2=1 . 
 when n At a relatively large scale, Fn It's also very large, and now we want to know, Fn Divided by the 10007 What's the remainder of theta. 
*/
#include<stdio.h>
#include<stdlib.h>
 
int N=10007;
 
/* To calculate Fibonacci function */
int Fibonacci (int n)
{
 int Fn;
 if (n==1 || n==2)
 {
 Fn=1;
 }
 else
 {
 Fn = (Fibonacci(n-1) + Fibonacci(n-2))%N;
 }
 return (Fn);
}
 
int main(void)
{
 int n,tap=1,F1,F2,Fn;
 
 /* Decide whether to continue the analysis 1 Number. */
 while(tap)   
 {
 /* Make sure the Numbers are valid */
     do     
 {
     printf("*************Fibonacci***************\n"); /* Simple menu */
         printf("Please enter a positive integer for analysis:\n");
 
  scanf("%d",&n);
 }while (n<1);
 
 /* To analyze */
 Fn=Fibonacci(n);
 printf("%d\n",Fn);
 
 /* Decide whether to continue the analysis 1 The number of */
 printf("enter 1 to continue,enter 0 to quit:\n");
 scanf("%d",&tap);
 printf("\n");
 }
 
 printf("Thank You.\n");
 return 0;
}

Using a recursive approach, run the analysis multiple times per run, and if you want to run the analysis only once per run, you just need to remove the while loop.


Related articles: