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.
Related
I'm new C++ programmer and just started doing some practice. I came up with the following code but didn't get the result expected by myself(very likely I'm wrong but I cannot make sense of it). I really appreciate your advice on it:
Here is my code:
#include <iostream>
using namespace std;
double simulate(double *p,double *v,double u)
{
int i = 0;
while (u>p[i])
{
u-=p[i];
i++;
}
cout << v[i];
}
int main()
{
double array1[] = {0.4,0.1,0.2,0.3};
double array2[] = {1.1,2.2,3.3,4.4};
simulate(array1,array2,0.5);
return 0;
}
The results give 2.2 while I expect 3.3 because: after two loops, u becomes zero so cannot execute the third loop, since we executed two loops, i becomes 2 that corresponds to index 2 in array 2, which is 3.3 instead of 2.2. Could any expert help me with this? Thanks a lot in advance!
You're incrementing I within the loop. Think of the logic.
-The while-statement does an if-check.
-You then decrement u but increment i. I now points PAST where u becomes <= 0.
This is in addition to the fact you can run off the end of your arrays, if your initial u is too big.
An addition note: please use meaningful variable names. I know this is just a practice, but it's best to get into the right habits from the beginning. Your future coworkers will appreciate it.
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.
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)
It's my first time dealing with recursion as an assignment in a low level course. I've looked around the internet and I can't seem to find anybody using a method similar to the one I've come up with (which probably says something about why this isn't working). The error is a segmentation fault in std::__copy_move... which I'm assuming is something in the c++ STL.
Anywho, my code is as follows:
bool sudoku::valid(int x, int y, int value)
{
if (x < 0) {cerr << "No valid values exist./n";}
if (binary_search(row(x).begin(), row(x).end(), value))
{return false;} //if found in row x, exit, otherwise:
else if (binary_search(col(y).begin(), col(y).end(), value))
{return false;} //if found in col y, exit, otherwise:
else if (binary_search(box((x/3), (y/3)).begin(), box((x/3), (y/3)).end(), value))
{return false;} //if found in box x,y, exit, otherwise:
else
{return true;} //the value is valid at this index
}
int sudoku::setval(int x, int y, int val)
{
if (y < 0 && x > 0) {x--; y = 9;} //if y gets decremented past 0 go to previous row.
if (y > 8) {y %= 9; x++;} //if y get incremented past 8 go to next row.
if (x == 9) {return 0;} //base case, puzzle done.
else {
if (valid(x,y,val)){ //if the input is valid
matrix[x][y] = val; //set the element equal to val
setval(x,y++,val); //go to next element
}
else {
setval(x,y,val++); //otherwise increment val
if(val > 9) {val = value(x,y--); setval(x,y--,val++); }
} //if val gets above 9, set val to prev element,
} //and increment the last element until valid and start over
}
I've been trying to wrap my head around this thing for a while and I can't seem to figure out what's going wrong. Any suggestions are highly appreciated! :)
sudoku::setval is supposed to return an int but there are at least two paths where it returns nothing at all. You should figure out what it needs to return in those other paths because otherwise you'll be getting random undefined behavior.
Without more information, it's impossible to tell. Things like the data
structures involved, and what row and col return, for example.
Still, there are a number of obvious problems:
In sudoku::valid, you check for what is apparently an error
condition (x < 0), but you don't return; you still continue your
tests, using the negative value of x.
Also in sudoku:valid: do row and col really return references to
sorted values? If the values aren't sorted, then binary_search will
have undefined behavior (and if they are, the names are somewhat
misleading). And if they return values (copies of something), rather
than a reference to the same object, then the begin() and end()
functions will refer to different objects—again, undefined
behavior.
Finally, I don't see any backtracking in your algorithm, and I don't
see how it progresses to a solution.
FWIW: when I wrote something similar, I used a simple array of 81
elements for the board, then created static arrays which mapped the
index (0–80) to the appropriate row, column and box. And for each of
the nine rows, columns and boxes, I kept a set of used values (a
bitmap); this made checking for legality very trivial, and it meant that
I could increment to the next square to test just by incrementing the
index. The resulting code was extremely simple.
Independently of the data representation used, you'll need: some
"global" (probably a member of sudoku) means of knowing whether you've
found the solution or not; a loop somewhere trying each of the nine
possible values for a square (stopping when the solution has been
found), and the recursion. If you're not using a simple array for the
board, as I did, I'd suggest a class or a struct for the index, with a
function which takes care of the incrementation once and for all.
All of the following is for Unix not Windows.
std::__copy_move... is STL alright. But STL doesn't do anything by itself, some function call from your code would've invoked it with wrong arguments or in wrong state. You need to figure that out.
If you have a core dump from teh seg-fault then just do a pstack <core file name>, you will see the full call stack of the crash. Then just see which part of your code was involved in it and start debugging (add traces/couts/...) from there.
Usually you'll get this core file with nice readable names, but in case you don't you can use nm or c++filt etc to dismangle the names.
Finally, pstack is just a small cmd line utility, you can always load the binary (that produced the core) and the core file into a debugger like gdb, Sun Studio or debugger built into your IDE and see the same thing along with lots of other info and options.
HTH
It seems like your algorithm is a bit "brute forcy". This is generally not a good tactic with Constraint Satisfaction Problems (CSPs). I wrote a sudoku solver a while back (wish I still had the source code, it was before I discovered github) and the fastest algorithm that I could find was Simulated Annealing:
http://en.wikipedia.org/wiki/Simulated_annealing
It's probabilistic, but it was generally orders of magnitude faster than other methods for this problem IIRC.
HTH!
segmentation fault may (and will) happen if you enter a function recursively too many times.
I noted one scenario which lead to it. But I'm pretty sure there are more.
Tip: write in your words the purpose of any function - if it is too complicated to write - the function should probably be split...
My professor has asked us to write a program that uses recursion to solve a fibonacci sequence. This is all pretty normal, but he's asked us to make our function return void. I've been working at this for a few days now and can't find a way to do this.
I have:
void fibonacci(double *n,double *x,double *y,double *result) {
if(*n == 1)
*result = 0;
else if(*n == 2)
*result = 1;
else
fibonacci(--n,n,(n-1),(n+(n-1))); }
Is what I'm doing right? I have never had to use
parameters in such ways before and I'm not sure
if I'm on the right track. For some reason it's
not compiling at the recursive call to fibonacci,
stating invalid pointer addition. Thanks!
Hint: problem is there: fibonacci(--n,n,(n-1),(n+(n-1))); or even just there --n. You're working with pointers
The compiler is right. You need to dereference the pointers in the call, if you use pointers.
But the simpler solution would be to use this prototype instead (and match all code to it) :
void fibonacci(int n, int *result).
I've replaced double by int, because I don't see why you'd use double to store integers.
I've removed x and y which you don't use in your function.
Since this is a homework, I won't provide working code, although a few points here:
Using a reference is simpler than using pointers
You really need to increase the result, not set it to 0 or 1. Therefore you need to pass to first function call by reference an int with assigned value of 0.
Consider the formula: f(n) = f(n-1) + f(n-2) for all n > 2; f(n) = 0 for n=1 and f(n) = 1 for n=2.
no it is not.
1st of all you are subtracting pointers to float (at --n) which might easily (even if you compile it and run it) produce access violation. It correctly complains though about types. The types that the function accepts are pointers and I bet you are passing floats.
Use this for a start:
void fibonacci(double n, double & result) {
if(n == 1)
result = 0;
else if(n == 2)
result = 1;
else {
// gotta figure that part out yourself
}
}
By declaring result as a reference, your modification will change the value of the actual parameter passed. Since this is C++ references should be preferred. You can still declare n as a normal value, because you do not want to modify it. The recursive call is your homework now :)
I think it must be like this:
void fibonacci_list()
{
int count,next=1,prev1=0,prev2;
printf("1");
for(count=2;count<=12;count++)
{
prev2=prev1;
prev1=next;
next=prev1+prev2;
printf("%d ",next);
}
printf("...");
return;
}