Below is my code. I tried to print the Fibonacci recursive function [at the very end] but it gave me segment fault. What is wrong with my code? I spent like 3 hours on this and couldn't figure it out. Can someone please be kind enough to give me some help? Thanks
int fibonacci (int x) {
if (x == 0) {
return 0;
}
else if (x == 1) {
return 1;
}
else {
return (fibonacci(x-1) + fibonacci (x + 2));
}
}
Most probably you're getting the segfault because your stack grows without control, and that's because of this line:
return (fibonacci(x-1) + fibonacci (x + 2));
calling fibonacci() with a value greater than the original causes the non-recursive case to never be reached, causing the stack to eventually overflow, or trying to do so, as the SO will detect this and terminates your process.
So, rewrite that line as this:
return (fibonacci(x-1) + fibonacci (x - 2));
Currently the recursion never ends because:
return (fibonacci(x-1) + fibonacci (x + 2));
should be
return (fibonacci(x-1) + fibonacci (x - 2));
The current code leads to the stack running out of memory because you keep adding function calls infinitely and at the point where the stack is out of memory you get the crash. You can see what is happening when you follow the flow of execution with a sample number:
fibonnaci(2) = fibonacci(1)+fibonacci(4)
= 1 + (fibonacci(3)+fibonacci(6))
= 1 + (((fibonacci(2)+fibonacci(5))+(fibonacci(5)+fibonacci(8)))
= 1 + .......
As you can see this never actually terminates.
Related
int Fun(int m, int n)
{
if(n==0)
{
return n + 2;
}
return Fun(n-1, m-1) + Fun(m-1,n-1) + 1;
}
I'm completely lost as to what the 1st case would visually look like for this function. I don't understand why the function has two parameters and why we only return 1 parameter at the end with our base case. What would be the process to work this out? Any input you want to use to explain to me is fine I was trying (3,3). Although, now that I'm thinking about it how would this function look like if one of the inputs was smaller than the other like (3,2) or (2,3)?
Note that return n + 2; simplifies to return 2;.
The function takes two arguments (parameters) and returns a single value. That's like the operation of adding two numbers that you were taught in your first year at school.
Whether or not Fun(n - 1, m - 1) is called before Fun(m - 1, n - 1) is not specified by the C++ standard. So I can't tell you what the first recursive call will look like. This gives compilers more freedom in making optimisation choices. Of course the order in which the functions are called has no effect on the eventual result.
The best way of analysing what happens in your particular case is to use a line by line debugger.
There is nothing special about recursive functions - they work exactly like non-recursive functions.
Fun(3,3) does this:
if(3==0)
{
return 3 + 2;
}
return Fun(2, 2) + Fun(2, 2) + 1;
It needs the value of Fun(2,2), which does this:
if(2==0)
{
return 2 + 2;
}
return Fun(1, 1) + Fun(1, 1) + 1;
And that needs Fun(1,1), which does
if(1==0)
{
return 1 + 2;
}
return Fun(0, 0) + Fun(0, 0) + 1;
and Fun(0,0) does
if(0==0)
{
return 0 + 2;
}
return Fun(-1, -1) + Fun(-1, -1) + 1;
which returns 2 since the condition is true.
So, Fun(1, 1) will do
return 2 + 2 + 1;
which is 5, and Fun(2,2) will do
return 5 + 5 + 1;
which is 11, and Fun(3,3) will do
return 11 + 11 + 1;
which is 23.
I'm sure you can work through other examples on your own.
in this function i check if the no. is one less than the power of 2 and then make recursive calls for 2^b - 1 and n - 2^b(this call keeps happening till the no. here is one less than a power of 2)
now I know the code is wrong but why does it give segmentation fault.
int countSetBits(int n)
{
if (n == 0)
return 0;
int b = floor(log2(n));
if ( (n + 1) & n == 0 ) {
return (1<<b)* floor(log2(n + 1));
}
return (n - 1<<b + 1) + countSetBits(n - 1<<b) + countSetBits(1<<b - 1);
}
The infinite number of (recursive) function calls causes stack overflow. The program's stack has become too large and tries to "overflow" into the next memory segment. This is not allowed, and hence the segfault.
The reasons for the errors are two-fold:
You are using floating point numbers, in floor and log2. Those are imprecise and won't give you the exactness you need for this task.
You are left shifting your numbers (making them bigger). I didn't follow the logic you wanted, but usually, the approach is to take the least bits out and then right-shift the numbers (>>)
Lastly, either use a debugger, or introduce debug couts to see what your program is doing, that will make it overall much easier.
this is a broad question, with a specific example. My question is, how do you figure out how to evaluate an algorithm or expression in a loop?
In the example beblow, I figured out how to use a loop to calculate a square root using a counter with the babylonian algorithm and it appears to be working ok.
But I can't figure out how evaluate this to a certain degree, say within .01 without using a counter. I see other people on the web doing it without a counter but the abililty to do it eludes me.
Here is my counter version:
int count(20);
while (count > 0 )
{
if (guess <= (guess * p) + guess)
prevGuess = guess;
else
r = input / guess;
guess = (guess + r) / 2.0;
count -= 1;
cout << "\nGuess = " << guess;
}
I've tried doing things like:
while ((guess - lastGuess) / lastGuess)
and
while(guess - lastGuess * .01)
But I either get just one interation or an infinite loop.
What is a good method to figure how to evaluate any algorithm inside a loop?
And I don't mean just for this little program, I mean for anything, even something like x + y = 2.
Would you do something like:
while(x + y !=2) {}
Thanks!
Normally this kind of computation can stop when the next iteration doesn't change the value by much; for example
for(;;) {
double next_v = (v + (n / v)) / 2;
if (fabs(v - next_v) < eps) break; // We got there
v = next_v;
}
where eps is the accuracy you want in the result.
You need to compare your error to your determined error limit, instead of zero as your attempts do.
You would use
while (abs((guess - lastGuess) / lastGuess) > .01)
for a relative error of .01, and
while(abs(guess - lastGuess) > .01)
for an absolute one.
In while (and every loop) there is condition which tells program when to stop it. This conditions must be some expression which return true or false value. Simpler, it's just an equation, or something which gives as clear answer: true or false. In your example expression like : ((guess - lastGuess) / lastGuess) isn't returning either true nor false. It returns some numbers etc.
Expression like ((guess - lastGuess) / lastGuess) == 4 will return true if ((guess - lastGuess) / lastGuess) will be equal to 4 and false if not. This example will work: while(x + y !=2). Program will call loop until x+y is equal 2.
I'm new to concept of recursion. I want to write a recursive function which take a float and integer as argument and call it recursively in a way that the float value remain constant and integer value changes
I write the following code:
#include <stdio.h>
float sum(float f, int k)
{
static float c;
c = f - k;
c = sum(f, k - 1);
return c;
}
int main()
{
float f, g = 10.00;
int i = 5;
f = sum(g, i);
printf("the sum of integer and float = %f", f);
}
When I compile it it shows no errors but when I run the program it shows a segmentation fault.
My question are following:
what is wrong with the code?
why it is showing segmentation error?
how to use recursion in a function which has more than one argument?
Please explain me with some example of recursive function which has two arguments.
The code is wrong because it can never end (I presume it fails with a stackoverflow error).
For recursion, you need two things
A base case
A recursive case that moves towards the base case
Looks like you've only got the second. I suspect sum should return when k is zero. Something like this hopefully makes sense:
float sum(float f, int k) {
if (k <= 0) {
// The base case
return f;
} else {
// The recursive case. This does one step of the work
// and moves towards the base case
return 1 + sum(f, k - 1);
}
}
Your recursion does not have a base (non-recursive), terminating case.
Every call to sum makes a recursive call to itself, this continues till your stackoverflows, resulting in a seg fault.
The recursion never stops, and eventually you run out of stack. You need to decide when it is time to stop the recursion. for example, if k equals 0 you don't call sum again, but exit with return.
float sum(float f ,int k)
{
static float c;
if (k > 0)
{
c=f-k; /// <<< why is this here? you ignore the value and overwrite it in the next step.
c=sum(f,k-1);
}
return c;
}
Of course there are additional problems: having c as static may be a problem that will affect the correctness of the calculation, and also the place I marked looks suspicious because you loose the value and overwrite it with the subsequent call to sum.
How about this?
#include <stdio.h>
float sum(float f, int k, float c) {
if (k == 0)
return c;
sum(f, k - 1, f - k);
}
The first thing I see is that your recursion has no termination. It will go on forever. Perhaps you want:
float sum(float f ,int k)
{
static float c;
c=f-k;
if (k != 0)
c=sum(f,k-1);
return c;
}
So that when k is zero the recursion stops. You had a stack overflow.
When you do recursion you need a status to end it.
So your code with changes:
#include <stdio.h>
float sum(float f, int k)
{
if(k == 0) return f;
return 1 + sum(f,k-1);
}
int main()
{
float f, g = 10.00;
int i = 5;
f = sum(g, i);
printf("the sum of integer and float = %f", f);
}
With that code, and your example f=10.00 and i=5
Call sum(10.0, 5)
return 1 + sum(10.0, 4)
1 + sum(10.0, 3)
1 + sum(10.0, 2)
1 + sum(10.0, 1)
1 + sum(10.0, 0)
10
1 + 10 = 11
1 + 11 = 12
1 + 12 = 13
1 + 13 = 14
1 + 14 = 15
return 15;
I don't understand what the "sum" function is for. Is it supposed to be adding f and k? In which case, there is no recursion; you should just add f and k: return f + k.
But to try to answer your questions:
There is no base case. This is the cause of the infinite recursion. Every recursive function needs a base case which is a condition under which it does not recurse. Your function recurses no matter what; therefore it will always recurse forever.
When recursion segfaults, it's usually due to a stack overflow (no pun intended); it means you are recursing forever and eventually running out of space.
You can use recursion in a function with more than one argument, just the same as any other function. Just call it with whatever the new values are for the next iteration.
Note that you often have a "constant" value, that doesn't change during the recursion. To do that, you just pass the value unchanged on the recursive call, so the same value is available at each step.
I was calculating the Fibonacci sequence, and stumbled across this code, which I saw a lot:
int Fibonacci (int x)
{
if (x<=1) {
return 1;
}
return Fibonacci (x-1)+Fibonacci (x-2);
}
What I don't understand is how it works, especially the return part at the end: Does it call the Fibonacci function again? Could someone step me through this function?
Yes, the function calls itself. For example,
Fibonacci(4)
= Fibonacci(3) + Fibonacci(2)
= (Fibonacci(2) + Fibonacci(1)) + (Fibonacci(1) + Fibonacci(0))
= ((Fibonacci(1) + Fibonacci(0)) + 1) + (1 + 1)
= ((1 + 1) + 1) + 2
= (2 + 1) + 2
= 3 + 2
= 5
Note that the Fibonacci function is called 9 times here. In general, the naïve recursive fibonacci function has exponential running time, which is usually a Bad Thing.
This is a classical example of a recursive function, a function that calls itself.
If you read it carefully, you'll see that it will call itself, or, recurse, over and over again, until it reaches the so called base case, when x <= 1 at which point it will start to "back track" and sum up the computed values.
The following code clearly prints out the trace of the algorithm:
public class Test {
static String indent = "";
public static int fibonacci(int x) {
indent += " ";
System.out.println(indent + "invoked with " + x);
if (x <= 1) {
System.out.println(indent + "x = " + x + ", base case reached.");
indent = indent.substring(4);
return 1;
}
System.out.println(indent + "Recursing on " + (x-1) + " and " + (x-2));
int retVal = fibonacci(x-1) + fibonacci(x-2);
System.out.println(indent + "returning " + retVal);
indent = indent.substring(4);
return retVal;
}
public static void main(String... args) {
System.out.println("Fibonacci of 3: " + fibonacci(3));
}
}
The output is the following:
invoked with 3
Recursing on 2 and 1
invoked with 2
Recursing on 1 and 0
invoked with 1
x = 1, base case reached.
invoked with 0
x = 0, base case reached.
returning 2
invoked with 1
x = 1, base case reached.
returning 3
Fibonacci of 3: 3
A tree depiction of the trace would look something like
fib 4
fib 3 + fib 2
fib 2 + fib 1 fib 1 + fib 0
fib 1 + fib 0 1 1 1
1 1
The important parts to think about when writing recursive functions are:
1. Take care of the base case
What would have happened if we had forgotten if (x<=1) return 1; in the example above?
2. Make sure the recursive calls somehow decrease towards the base case
What would have happened if we accidentally modified the algorithm to return fibonacci(x)+fibonacci(x-1);
return Fibonacci (x-1)+Fibonacci (x-2);
This is terribly inefficient. I suggest the following linear alternative:
unsigned fibonacci(unsigned n, unsigned a, unsigned b, unsigned c)
{
return (n == 2) ? c : fibonacci(n - 1, b, c, b + c);
}
unsigned fibonacci(unsigned n)
{
return (n < 2) ? n : fibonacci(n, 0, 1, 1);
}
The fibonacci sequence can be expressed more succinctly in functional languages.
fibonacci = 0 : 1 : zipWith (+) fibonacci (tail fibonacci)
> take 12 fibonacci
[0,1,1,2,3,5,8,13,21,34,55,89]
This is classic function recursion. http://en.wikipedia.org/wiki/Recursive_function should get you started. Essentially if x less than or equal to 1 it returns 1. Otherwise it it decreases x running Fibonacci at each step.
As your question is marked C++, I feel compelled to point out that this function can also be achieved at compile-time as a template, should you have a compile-time variable to use it with.
template<int N> struct Fibonacci {
const static int value = Fibonacci<N - 1>::value + Fibonacci<N - 2>::value;
};
template<> struct Fibonacci<1> {
const static int value = 1;
}
template<> struct Fibonacci<0> {
const static int value = 1;
}
Been a while since I wrote such, so it could be a little out, but that should be it.
Yes, the Fibonacci function is called again, this is called recursion.
Just like you can call another function, you can call the same function again. Since function context is stacked, you can call the same function without disturbing the currently executed function.
Note that recursion is hard since you might call the same function again infinitely and fill the call stack. This errors is called a "Stack Overflow" (here it is !)
In C and most other languages, a function is allowed to call itself just like any other function. This is called recursion.
If it looks strange because it's different from the loop that you would write, you're right. This is not a very good application of recursion, because finding the n th Fibonacci number requires twice the time as finding the n-1th, leading to running time exponential in n.
Iterating over the Fibonacci sequence, remembering the previous Fibonacci number before moving on to the next improves the runtime to linear in n, the way it should be.
Recursion itself isn't terrible. In fact, the loop I just described (and any loop) can be implemented as a recursive function:
int Fibonacci (int x, int a = 1, int p = 0) {
if ( x == 0 ) return a;
return Fibonacci( x-1, a+p, a );
} // recursive, but with ideal computational properties
Or if you want to be more quick but use more memory use this.
int *fib,n;
void fibonaci(int n) //find firs n number fibonaci
{
fib= new int[n+1];
fib[1] = fib[2] = 1;
for(int i = 3;i<=n-2;i++)
fib[i] = fib[i-1] + fib[i-2];
}
and for n = 10 for exemple you will have :
fib[1] fib[2] fib[3] fib[4] fib[5] fib[6] fib[7] fib[8] fib[9] fib[10]
1 1 2 3 5 8 13 21 34 55``