Task:
- Problem: Take two non-negative integers and return their product (the result of multiplying the two together).
- The function header should be `int timeser(int x, int y)`
- Restrictions: You are allowed to use anything that `adder` was allowed to use, and also allowed to use `adder` (and of course, `timeser` itself)
#include <iostream>
usingnamespace std;
int adder(int x, int y)//adder
{
if(x==0)
return y;
elseif(y==0)
return x;
elsereturn adder(--x,++y);
}
int timeser(int x,int y)//multiplier
{
if(x==0||y==0)
return 0;
elseif(y==1)
return x;
elseif (x==1)
return y;
elsereturn timeser(--y,adder(x));
}
int main()
{
int x,y;
cout<<"Enter two integers: ";
cin>>x>>y;
cout<<timeser(adder(x,y));
return 0;
}
I just started the recursive section and do not understand much of it.. so obviously practice makes perfect but i need help to learn how to perfect it. Could you help me solve and explain it?
I am not sure about what you are trying to do exactly.
adder(x,y) should return x+y? In that case why you return adder(--x, ++y)?
(it is correct and produces a sum of x,y using recursivity, but it seems a bit expensive).
Or adder(x,y) is a part of the assignment and you must use it in someway to make product?
(timeser is a quite confusing name for the function, try something more focused - multiply??)
note: (in line 21): adder(x) is an error... adder requires two parameters.
I readed restrictions before posting and it seems to me that restrictions are respected.
You use infact adder(x, y) and timeser(x, y) and decrement y (no use of operands, loops or other things)
It seems to me that suits: use only restrictions in adder (it means: don't use operands, but allowed to use increment / decrement, don't use loops like for, etc etc) and use adder and timeser if needed.
If you see anything restricted please explain.
NOTE: this is the only solution possible I could find that use adder (if it is defined so you are expecting to use it) and only in a recursive way. (infact a multiply is a recursion of sum of the same value for n times).
EDIT: your link is confirming that also other users before me gave you the same answer I am giving to you so I am not wrong (note: I didn't know the existance of that post and I had not see the others answers before replying you).
Note a thing (probably you see it but I will underline it)...
when you use recursivity you need a stop-case-recursivity management.
in case of adder stop-case is x==0 (you decrement x until reach 0. when it is 0 it encounters the case where adder returns a fixed value).
the same for the timeser... in that case the stop case is y == 1 (you will multiply until y in adder(x, timeser(x, --y) is decremented to 1 -> then returns a fixed value).
Other cases (y == 0 for sum) and (x==1, x==0, y==0) have only the objective to manage special cases to avoid possible errors but not provide an actual stop-case (becouse adder recursively subtract x and timeser recursively subtract y).