I have the following task:
Write a program that asks for a number and a power. Write a recursive
function that takes the number to the power. For example, if the
number is 2 and the power is 4, the function will return 16.
I wrote a program and there are no errors when I compile it, but when I start the program and enter a value gives an error saying "Stack Overflow". I suppose my recursive function became infinite but I have no idea how to write it in other way.
This is my code:
#include <iostream>
using namespace std;
int powpow(int number);
int main(){
cout<<"Enter number:";
int x;
cin>>x;
cout<<"The result of ("<<x<<" * "<<x<<") * "<<x*x<<" is: "<<powpow(x);
system("pause");
return 0;
}
int powpow(int number){
int result = number*number;
return powpow(result);
}
You have no terminating condition for your recursion, so it runs forever.
It sounds like maybe you don't have a good grasp of recursion, so I'd like to start with something a little simpler, the Fibonacci sequence.
Any time we define a function in terms of recursion, we need to first define a base case(s). In the case of Fibonacci, we have 2 base cases:
F(0) = 0
F(1) = 1
That says, in english, "F of 0 is 0, F of 1 is 1". Or even more simply, if we pass 0 to function F, we will get 0 back. If we pass 1, we will get 1 back.
Once we have the base cases defined, then we need to look for a recurrence relation. In the case of Fibonacci, we have the following recurrence:
F(n) = F(n-1) + F(n-2)
So for n >= 2, we can use the above recurrence. Why? Well, lets try it for n = 2.
F(2) = F(n-1) + F(n-2)
= F(1) + F(0)
= 1 + 0
= 1
So now we know that the answer to F(2) is 1. And what's more, we can now compute the answer to F(3). Why? Well, what do we need to compute F(3)? We need F(2) and F(1). We now have both of those answers since F(1) is a base case, and we just solved F(2) above.
So, now let's try to write a piece of pseudo code to solve F.
function F(int n) {
// handle base cases
if (n equals 0)
return 0
if (n equals 1)
return 1
// recurrence
return F(n-1) + F(n-2);
}
Note that in a recursive function, we always handle the base cases at the beginning of the function. We cannot define this recurrence if we don't have base cases in place, otherwise, we will have no terminating condition for our recurrence. So that's why you always put the base cases at the beginning of the function.
Now, given the above explanation, another good exercise would be to write a recursive function for the factorial function. So, follow these steps:
1. Define the base case (use wikipedia article for hints).
2. Define recurrence in terms of base case
3. Write pseudo code to solve the recurrence, and be sure to put base case(s) at beginning of function, and recurrence at end.
Once you grasp these steps, then moving on to the power recurrence should make much more sense to you.
Your function
does not what it should do
has no termination condition
Try to think about this: How can your function return x^y when it only takes one number as a parameter. Then, think about how you raise number to a power and the implementation should be obvious.
Recursive routines always need a "trivial" or "base" case. Think about what you wrote, pass in 1 for x, what will the stop the recursion?
powpow(1)
result = 1*1
call powpow(1)
result = 1*1
call powpow(1)
result = 1*1
call powpow(1)
adinfinitum (or until you exeed the stack)
Related
There is an issue with the recursive definition of the fibonacci sequence when it comes to efficiency. It is defined as follows:
private fib(int n) {
if(n < 2) return n;
else return fib(n - 1) + fib(n-2);
}
Suppose we call fib(5). This makes 1 call to fib(4) , two calls to fib(3), three calls to fib(2), five calls to fib(1) and three calls to fib(0).
In his book
Programming Abstractions in Java by Eric Roberts
Roberts mentions that we can resolve this efficiency issue by realizing that the fibonacci sequence is just a special case of the additiveSequence(int n, int t0, int t1) method. Basically, the Fibonacci sequence is just an additive sequence that strictly begins with 0 and 1. There are an infinite number of sequences that match the recurrence relation expressed by Fibonacci.
The author resolves the efficiency issue as follows:
private int fib(int n) {
return additiveSequence(n, 0, 1);
}
So my questions is, by making the fib sequence a wrapper for the more general additiveSequence method, are we really improving efficiency ? Wouldn't the implementation of additiveSequence have the same exact "problem" in terms of efficiency that fib had, given that it does follow the same exact reccurence relation ?
Here's an example implementation of an additive sequence calculation, where ti = ti-1 + ti-2:
int additiveSequence(int n, int t0, int t1) {
if(n==0) return t0;
if(n==1) return t1;
return additiveSequence(n-1, t1, t0+t1);
}
This method returns the n-th value in the series. Work through some examples and you should be able to convince yourself that each ti will be calculated only once. Compare that with your naively implemented fib method and you can see why this approach is much faster.
The Fibonacci series is this kind of additive sequence, with the starting conditions t0 = 0 and t1 = 1. There's nothing particularly special about it, other than the fact that the obvious way to code it is a poor one. The author's point, presumably, is that implementation makes a huge difference in processing time. It does not appear to be clearly explained, however.
Can someone please help me understand this recursive function? Ive been following an online tutorial but Im stuck at this part:
int factorialFinder(int x){
if(x==1){
return 1;
}else{
return x * factorialFinder(x-1);
}
}
So I know this function is used to calculate the factorial of an integer x but I dont understand the return x * factorialFinder(x-1);
does this line multiple the values for x by x-1 or does it first look for the base case THEN multiply the values? The way it was explained to me was that the function looks for x==1 and then it multiplies the values of x but this makes no sense to me.
Lets consider x=4
so function call stack would be
factorialFinder(4) returns 4*factorialFinder(3)
factorialFinder(3) returns 3*factorialFinder(2)
factorialFinder(2) returns 2*factorialFinder(1)
factorialFinder(1) returns 1 *base condition*
Now just substitute return values. Since its a stack, last function call will be evaluated first
So
factorialFinder(1) = 1
factorialFinder(2) = 2*1
factorialFinder(3) = 3*2*1
factorialFinder(4) = 4*3*2*1
Looks are you are playing around recursion for the first time. It looks little confusing initially but its a great problem solving approach that lets you solve problems with minimal code. Explore it further!! and Hope it helps.
I wrote a recursive function that computes the sum of an array of double. For some reasons, the value returned by my recursive function is not correct. Actually, my recursive sum does not match my iterative sum. I know I made a little mistake somewhere, but I can't see where. Your help will be very appreciated. I only pasted the recursive function. I am using C++ on Visual Studio. Thanks!
double recursive_sum(double array_nbr[], int size_ar)
{ double rec_sum=0.0;
if( size_ar== 0)
return -1;
else if( size_ar> 0)
rec_sum=array_nbr[size_ar-1]+recursive_sum(array_nbr,size_ar-1);
return rec_sum;
}
//#### Output######
The random(s) number generated in the array =
0.697653 | 0.733848 | 0.221564 |
Recursive sum: 0.653066
Iterative sum: 1.65307
Press any key to continue . . .
Well, because sum of no elements is zero, not minus one.
if (size_ar == 0.0)
return 0.0;
Think about it this way: sum(1,2,3) is the same as sum(1,2) + sum(3) just as it is the same as sum(1,2,3)+sum() — in all three cases, you add 1, 2, and 3 together, just in a slighlty different ways. That's also why the product of no elements is one.
Try changing "if( size_ar== 0) return -1;" to return 0.
While this does not account for the large discrepancy in your output, another thing to keep in mind is the ordering of operations once you have fixed the issue with returning a -1 vs. 0 ... IEEE floating point operations are not necessarily commutative, so make sure that when you are doing your recursive vs. iterative methods, you add up the numbers in the exact same order, otherwise your output may still differ by some epsilon value.
For instance, currently in your recursive method you're adding up the values from the last member of the array in reverse to the first member of the array. That may, because of the non-commutative property of floating point math, give you a slightly different value (small epsilon) than if you sum up the values in the array from first to last. This probably won't show on a simple cout where the floating point values are truncated to a specific fixed decimal position, but should you attempt to use the == operation on the two different summations without incorporating some epsilon value, the result may still test false.
How would you find a T(n) run-time (not the big O run time) for a function that has two inputs? Do you just consider the a input your 'n'?
int h(int a, int b) {
if (a > 0) {
return h(a-1, a+b);
}
else {
return 0;
}
}
In this case we just need to consider a since the length of this algorithm isn't dependent on b.
In other words since we can pass in 20000 or -2 for b and not impact our time in the slightest (ignoring the actual time of adding a+b) we shouldn't have to consider b in our calculations.
In a more general case, if the input did depend on a and b we would simply account for this in our time complexity function. In other words it would be T(a, b) not just T(a).
as this function recurs only on a and a is decreasing by 1 in each step, it would give linear complexity. So answer would be T(a).
Given that for each and every (a,b)-pair the function value is zero - the recursion will always end in the else-branch - the compiler may be smart enough to reduce the code effectively to "return 0" for the whole body and leave all the if/else and recursion stuff out, resulting in O(1) complexity and corresponding run time.
Hey Guys. I need help understanding my hw assignment. I am starting out in C++ and don't know that much. I do know the basics of a stack and fibonacci sequence. However I do not exactly understand the problem given to me and need not the code to solving the problem but help clarifying some steps. Here's the hw:
"By completing this project you will become familiar with using recursion and creating ADTs in C++.
Create an integer stack ADT (you may Modify the IntStack ADT given to you in the lecture notes) such that it has a maximum capacity of at least 256 elements. Also add whatever is needed such that it will print out its contents (left-to-right, with the top of the stack on the right) if it is printed to a C++ ostream - such as cout). This stack should be designed such that it will only hold meaningful values greater than zero. Values less than or equal to zero should be printed out as a '?'.
Write a recursive implementation of the Fibonacci sequence discussed in class. Also - create an instance of your stack ADT that persists between calls (it can't be a local variable), and at each step, push a non-meaningful value into it until the value at that stage is determined, then pop it off, and push in the determined value and print the entire stack before returning.
Your program should ask for the position N in the Fibonacci sequence to be determined and then it should output the result of the function call. Example output (including the output from your recursive function) follows:
Enter the position in the Fibonacci sequence to determine: 5
?-?-?-1
?-?-?-1
?-?-2
?-?-1
?-3
?-?-1
?-?-1
?-2
5
Fibonacci(5) = 5
What exactly is the output here? Is it printing out the stack as it calculates the 5th position? also Any ideas on how to implement the Fibonacci into a stack in C++? Should these values be stored in array, list or it doesn't matter? I'm a noob so any help would be much appreciated. Thanks
Yes, it's calculating 5th fibonacci number (which happens to be 5, that's a bit confusing), but look at what you calculate when you call fibonacci(5), assuming the following code for fibonacci:
int fibonacci(int n) {
if (n <= 1) return n;
else if (n == 2) return 1;
else return fibonacci(n-1) + fibonacci(n-2);
}
here are the function calls to calculate fibonacci(5):
f(5)
-> f(4)
-> f(3)
-> f(2)
-> f(1)
-> f(2)
->f(3)
-> f(2)
-> f(1)
If you look at this as a binary tree, the output they gave you was a post-order tree traversal, with the amount of ? being the depth of that stack, and the number being the value of that node.
So just do what the function does and every time you see return, write what you return (with the ?'s before it):
The first function that returns is the first f(2), at depth 4: print ?-?-?-1
The second return is the f(1) below it: print ?-?-?-1
The third return is the parent of f(2) and f(1), which has depth 3 and value f(2)+f(1)=2: print ?-?-2
And so on until you return f(5) at depth 0 and value 5
Beak your entire problem into smaller parts which can be solved/implemented by themselves. In this case there are two main parts:
Stack -- Implement a standard stack class according to the details given in the question. It may help to list them all in point form.
Fibonacci -- Use the stack class to generate the Fibonacci series recursively. The stack is your storage mechanism for this exercise.
The example output ?-?-?-1 can be understood as the following stack operations:
push 0
push 0
push 0
push 1
print
I leave printing the stack to you and address the confusing part of using the stack to store marker ("the non meaningful" number) and result. Here is the partial pseudo code:
procedure fib(n)
push a marker (say a zero) to a global stack
if n is 1 or 2 then
result = you_know_what
else
calculate fib(n-1)
pop the stack ==> fib_n_minus_1
calculate fib(n-2)
pop the stack ==> fib_n_minus_2
result = fib_n_minus_1 + fib_n_minus_2
endif
pop the marker off the stack and discard
push the result into the stack
print the stack
end fib
The key to note here is fib() does not return a value. Instead, it pushes the return value into a global stack.