1
Hello. How could you know how many times a function is called recursively by its code?
For example, in the code below, how to know how many asterisks the function prints for a given value n?
int fibonacci(int n) {
printf("*");
if ((n == 1) || (n == 2))
return (1);
return (fibonacci(n-1) + fibonacci(n-2));
}
It’s just having a variable that controls this, like everything you want a state, but it depends on how you want it to know how to do it. Anyway when it starts to have a lot of complication it is better not to do recursive.
– Maniero
A global variable does not help?
– MSLacerda
So I actually wanted a mathematical expression for that. For example, for n = 3 prints 3 asterisks, for n = 5 prints 9 f(3) = 3 f(5) = 9 I don’t want the program to do that. I want a way to understand how to calculate this number.
– Lucas Lopes
Are you interested in the complexity of your algorithm? If it is interesting to include this in your question...
– MSLacerda
Yeah, I think that’s what I want.
– Lucas Lopes
If to use a global variable it makes no sense to do something recursive.
– Maniero
Possible duplicate of How to optimize this function for Fibonacci sequence?
– Victor Stafusa
Although the question I marked as duplicate is Javascript instead of C, the code there has the same functioning and the answers there should serve to answer your question.
– Victor Stafusa
Let me ask: do you want to know this for any function? For example, "I want to know how often my function
int quadrado (int n)
was called"? If so, I believe you could use more professional tools such as the GCOV.– Anderson Torres
Actually this is an exercise, a question was given: "In the program below, how many times * is printed for an input n?"
– Lucas Lopes