Recursive Fibonacci printing

Asked

Viewed 11,043 times

5

I’m having problems with the recursive function Fibonacci, in the exercise you ask to print inside the function or even using an auxiliary recursive function, but you can’t print in the main function, I tried everything to print, but they keep repeating, the recursive function Fibonacci I know how to do, just missing the impression, follows the enunciation and ask someone to give me a light.

"The Fibonacci sequence is defined by:

  • F0 = 0
  • F1 = 1
  • Fn = Fn - 1 + Fn - 2, for n > 1

Develop a recursive function that calculates and prints the first n Fibonacci sequence numbers. The function must have the following signature:

int fibonacci (int n);

The function shall print the first n numbers separated by spaces, by example, for n = 10:

0 1 1 2 3 5 8 13 21 34"

  • 3

    Just to say that there are other forms besides recursion: http://answall.com/questions/177138/como-optimizar-essa-fun%C3%A7%C3%A3o-para-sequ%C3%Aancia-de-fibonacci/177269

  • 1

    I just want to make it clear that Fibonacci is an example of where nay whether to use recursion, at least not without some other trick. See the question @Marcusbecker linked above for more details.

  • It is mandatory the use of recursion, are test exercises on the content. TMB does not like recursion with Fibonacci, it is very long execution, but it is a course and this is the theme

  • 4

    @Marcelodesousa Yes, I know. My comment above was just to make it clear to some casual visitor that bumping into this question that using recursion in Fibonacci in a simple and straightforward way is not a good idea.

5 answers

2

Remember what it is about the function it is the sum of the predecessor by the previous predecessor , it begins with two terms the 0 and the 1.

  • fórmula : 0, 1,(1+0),((1+0)+1),(((1+0)+1)+(1+0))....

transforming this expression into a function we can arrive at Fibro(n - 1) + Fibro(n - 2) where n is the number of terms considering , of course , that it is being done in a decreasing way (so that need to pass only one parameter value).

recursively made each sum of your terms will be stored in a stack which after arriving at the base condition will be terminated and will have your terms unsealed.

Obs: I leave an example in C# the reasoning is the same

  static void Main(string[] args)
    {
        int n=0;
        Console.WriteLine("Digite o tamanho da sequencia");
        n = int.Parse(Console.ReadLine());

        Console.WriteLine("resultado");
        for (int c=0; c<=n; c++) {
          Console.Write(" "+Fibro(c + 1));//imprimi aqui mas você pode imprimir dentro da recursão mas vai perder o objetivo da recursão de mostrar uma pilha 
        }
        Console.ReadKey();

    }

    public static int Fibro(int n){
        if (n == 1 || n == 0)
        {
            return 1;
        }
        else {

            return Fibro(n - 1) + Fibro(n - 2);//recursão 

        }

     }

0

If only the printing is missing, each time you calculate the value of the number is enough

printf("Fibonacci é: %d", fibonacci);

Where %d is just a "Holder" for your number, which is passed in the second parameter.

  • You speak within the function? Here tested and nothing, as said the impression has to be within the function or using an auxiliary function

  • 1

    Inside your recursive method, before calling Fibonacci again from a print of your number. It should work... Otherwise post your current code @Marcelodesousa

0

This is a version of the Fibonacci algorithm using an auxiliary vector, which enables the calculation of values up to 50, instantaneously. For larger values, it will be necessary to use long int, long int or others.

#include <stdio.h> 
#include <stdlib.h> 

void calculaFibonnaci();
int fibonnaci();

int vetor[1000];

void calculaFibonnaci(int i) { 

    if(i==1 || i==2) {
        vetor[i] = 1;
    }
    else { 
        vetor[i] = fibonnaci(i-1) + fibonnaci(i-2);
    }
}

int fibonnaci(int i)
{
    if(vetor[i]==0) {
        calculaFibonnaci(i);
        printf("%d ", vetor[i]);
    }
    else {
        return vetor[i];
    }   
} 

int main(int argc, char* argv[]) 
{
    int i, N;
    int *vetor;
    printf("Digite quantos termos da série de fibonacci você deseja: ");
    scanf("%d", &N);

    for(i=1; i<=N; i++)
        fibonnaci(i);

    return 0;
} 
  • 1

    If you notice my comment on line 3, you will see that you will have problems for large values, for example, 40, 45. If you want to improve your recursive Fibonnaci, I recommend a survey on using a vector to store the values already calculated, avoiding recalculation.

  • I cannot use the main function as an auxiliary, the main function must call the recursive function Fibonacci and use an auxiliary function inside the rescursiva, the function Fibonacci must call the function for printing, without going through the main or printing inside itself

  • Relax, I implemented the use of the vector, but I don’t think it solves your problem yet.

  • There, I believe your problem is now solved.

  • The function signature has to be int Fibonacci (int n); and without the use of main, the main function must be used only to call the recursive function.

  • This solution is more intelligent because it allows the calculation of Fibonnaci for large values. I will adapt it to enter as of your exercise

  • Just out of curiosity, you could create a global vector, bypassing this need to be int Fibonnaci (int n);

  • The signature int Fibonnaci (int n); is mandatory, but a global vector can be used yes

  • Okay, now you have a global vector, according to your statement.

  • Main function cannot print anything.

Show 6 more comments

-1

#include<stdio. h> #include<stdlib. h> #include<string. h>

int Fib(int n){

if(n == 0){
    
    return 0;
    
}
if(n < 3){
    
    return 1;   
    
}else{
    
    return fib(n-1) + fib(n-2);

}

}

int main(void){

int n;
int r;
int i;

scanf("%d", &n);

for(i = 0; i <= n; i++){
    
    r = fib(i);
    
    printf("%d ", r);       
}



return 0;

}

-3

Fibonacci series in C:

#include <stdio.h>
#include <stdlib.h>

unsigned long fibonacci();
unsigned long v[sizeof(int)] ;

unsigned long fibonacci(int n) {
   if (n <= 0)
      return -1;
   if((n <= 2)  && v[n] == 0) {
      v[n] = 1;
      printf("%lu ", v[n]);
   }
   else if (v[n] == 0) {
      v[n] = fibonacci(n-2) + fibonacci(n-1);
      printf("%lu ", v[n]);
   }

   return v[n];
}

int main(int argc, char* argv[]) {
   int in;
   printf("Entre com o tamanho da série: ");
   scanf("%d", &in);
   fibonacci(in);
   return 0;
}

Fibonacci series in Python:

d = {}
def fib(n):
  if (n < 2):
    d[n] = n
    return d[n]
  if (d.keys().__contains__(n)):
    return d[n]    
  d[n] = fib(n - 2) + fib(n - 1)    
  return d[n]  

for i in range(0,101):
  print('fib(',i,'): ', fib(i))
  • 1

    Antonio, the question is in C and you are not explaining how your code works so that the author understands and reproduces in another language.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.