Question regard to this recursion function - c++

A code to find a factorial of an input n:
#include <iostream>
using namespace std;
long long factorial(int num) {
if (num == 0) {
return 1;
}
else {
return num * factorial(num-1);
}
}
int main() {
int num;
cin >> num;
cout << factorial(num) << endl;
}
My questions are:
Here written factorial(num-1) then how can the variable num get decreased per loop ? The function will permanent use num-1 as its argument but num is not saved. I mean there should be num--; in the function. I have tried and printed out variable num at the end of the program and it was the same, num wasnt 0.
Here written if (num == 0) { return 1; } . When num get decreased to 0 then shouldn't the function takes 1 as it final value ? But it doesn't. Just like variable, when you write a = 1 at the end of the program; then doesnt matter what calculation happened to a before, the final value of a will be 1. And as I understand return 1; has the same effect, doesnt it ?
Many thanks

Recursive functions work exactly like non-recursive functions - there is no "loop" and nothing gets decremented.
Perhaps the substitution method could help.
Consider factorial(2).
If we replace num with 2 in the function's body we get
if (2 == 0) {
return 1;
}
else {
return 2 * factorial(2-1);
}
In order to calculate this, we need factorial(1), which becomes
if (1 == 0) {
return 1;
}
else {
return 1 * factorial(1-1);
}
And now we need factorial(0):
if (0 == 0) {
return 1;
}
else {
return 0 * factorial(0-1);
}
This is clearly 1, so now we can move back up and insert the calculated values in place of the function calls.
factorial(1):
if (1 == 0) {
return 1;
}
else {
return 1 * 1;
}
which is 1, and then factorial(2):
if (2 == 0) {
return 1;
}
else {
return 2 * 1;
}
which is 2.
Note that there is no "connection" between the recursive calls - they don't share any variables or other data, their arguments just happen to have the same name - and return does not return to the "topmost" caller but only to the most immediate one, just like other functions.

The original variable "num" is never decreased there.
It's an integer, thus, is a value type. So, everytime by writing factorial(num-1) you create a new variable with the value (num-1) and pass it to the function. (e.g. if num was 5 then it would be like calling factorial(4))
Again, "num" never gets decrased. You just pass a new variable that has the num-1 value. So, in the previous loop when the num was 1, and you called factorial(num-1) you just passed it's like calling factorial(0), and here that 0 was just checked in the if statement and exited by returning 1.

Lets break this down with a concrete example. If you call factorial(5) then what happens is you run if (num == 0), which is false, so you then run return num * factorial(num-1);, where num is 5 so it's return 5 * factorial(4). Now, in order for return to return, it needs to evaluate factorial(4). Just like factorial(5), factorial(4) becomes return 4 * factorial(3), this happens for 3, 2 and 1. Once you are in factorial(1), you get return 1 * factorial(0), and factorial(0) passes if (num == 0), so it is just return 1.
Putting all that together you get
return 5 * 4 * 3 * 2 * 1 * 1

Related

how to return how many times has a recursive function been called in C++?

void funct(int n)
{
int steps = 0;
if(n != 1){
steps++;
if((n % 2) == 0){
funct(n/2);
}
else if((n % 2) != 0){
funct((3*n + 1));
}
cout << steps << " ";
}
}
I tried this code, but it prints 1 in every time; I want my code to print how many times it has ben called.
steps is a local variable in funct each call to funct has its own copy. You need to pass a single variable through all calls to funct in order to count correctly.
void funct(int n, int& steps)
{
if(n != 1){
steps++;
if((n % 2) == 0){
funct(n/2, steps);
}
else if((n % 2) != 0){
funct((3*n + 1), steps);
}
}
}
int main()
{
int steps = 0;
funct(5, steps);
cout << steps << "\n";
}
As it stands, the steps variable in your function is a local variable of automatic storage duration. The latter means that it will be re-initialized to zero on each call of the function.
You can add the static keyword to the declaration to make it so that the initialization (to zero) happens only the first time the function is called (cppreference) and, from then on, the modified value will be maintained across subsequent calls of the function (until or unless it is explicitly reset1).
However, even with that, if you want to see a 'rolling' count, you will need to put the cout line (where the value is reported) before you make either of the recursive calls.
Here is a possibility (I have also changed your test condition from n != 1 to n > 1, in order to prevent the potential infinite recursion mentioned in the comments to your question):
void funct(int n)
{
static int steps = 0; // Initialized only the first time this line is reached
if (n > 1) {
steps++;
std::cout << steps << " ";
if ((n % 2) == 0) {
funct(n / 2);
}
else if ((n % 2) != 0) {
funct((3 * n + 1));
}
}
}
1 One way to implement this "explicit" reset would be to do so in an else block, when the recursion chain is complete. The following code shows how to do this, along with a short main that shows how the behaviour works on multiple, sequential 'top-level' calls to funct:
#include <iostream>
void funct(int n)
{
static int steps = 0;
if (steps == 0) {
std::cout << "Top-level call with " << n << "... ";
}
if (n > 1) {
steps++;
std::cout << steps << " ";
if ((n % 2) == 0) {
funct(n / 2);
}
else if ((n % 2) != 0) {
funct((3 * n + 1));
}
}
else {
std::cout << std::endl;
steps = 0;
}
}
int main()
{
funct(5);
funct(9);
funct(8);
return 0;
}
Output:
Top-level call with 5... 1 2 3 4 5
Top-level call with 9... 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Top-level call with 8... 1 2 3
Another way would be to use a 'special' value (like, for example, a negative number) to change the behaviour of the function so that, if such a value is passed, the function resets steps to zero and then returns immediately.
Let the function return how many times it has been called. And that is always one more than the number of calls that the recursive invocation reported:
int funct(int n)
{
int steps = 0;
if(n != 1){
if((n % 2) == 0){
steps = funct(n/2);
}
else {
steps = funct((3*n + 1));
}
}
return steps + 1;
}
int main()
{
int steps = funct(5);
cout << steps << "\n";
}

why am I getiing 0 as a result,I want the return value as the result?

I want the result to be the returned value from the mystery function,but the result is always 0 .but I want the program to return a value that's collected from the mystery function
#include <iostream>
using namespace std;
int Mystery(int n)
{
// int k;
if (n <= 1)
{
return 0;
}
else
{
int k = n;
for (int i = 1; i <= n; i++)
{
k = k + 5;
}
cout << ((k * (n / 2)) + (8 * (n / 4)));
cout << "\n ";
return ((k * Mystery(n / 2)) + (8 * Mystery(n / 4)));
}
}
int main(void)
{
int i, n;
cout << "Enter n:"; //array size
cin >> n;
int result = Mystery(n);
cout << "The result is " << result;
return 0;
}
Let's desk check what happens when you call Mystery(2). The final return value is:
((k* Mystery(n/2)) + (8* Mystery(n/4)))
We know that n == 2 so let's substitute that:
((k* Mystery(1)) + (8* Mystery(0 /* by integer division of 2/4 */)))
This will call the function recursively twice with the respective arguments 1 and 0. But we know that the terminating case n <= 1 returns 0, so we can substitute that:
((k* 0) + (8* 0))
Anything multiplied by zero is zero, so this reduces to 0 + 0 which is also zero. It doesn't even matter what k is.
Quite simply, the terminating case for this recursion mandates that the result is always zero.
In the terminating case the return value is zero.
In the recursive case, the recursive call result is multiplied with another value to produce the return value.
Therefore, the result is always going to be zero for any n.
I'm not sure exactly how this function is supposed to work as you have not explained that, but changing the terminating case to return 1; may solve the problem.
I don't expect which result you want, but I think you can get write result when you correct conditions like
if (n == 0)
return 0;
if (n == 1)
return 1;
I hope it returns the right result.

Recursive function to counting specific digit

I need to create a recursive function that counts the 2 and 6 from the number a user inputs.
For example if the user enters 26827 the count is 3.
It works with certain numbers and certain numbers it doesn't. Can someone please modify my function making sure its recursive and using very basic C++ language as I have used. Thank you! (I believe something is wrong with return type.)
int count(int n) {
static int count = 0;
if (n == 2 || n == 6) count++;
if ((n % 10 == 2) || (n % 10 == 6)) {
count++;
count(num / 10);
}
else return count;
}
One liner for fun.
int f(int n) {
return n == 0 ? 0 : (n%10==2 || n%10==6) + f(n/10);
}
int count(int n) {
if(n <= 0) return 0; // Base Condition
int countDig = 0; // Initalizing Count of digits
if(n % 10 == 2 || n % 10 == 6) // Checking whether the LSB is 2 or 6
countDig ++; // If it is then incrementing the countDig
countDig += count(n / 10); // Calling the recurive function by sending the number except its LSB
//And incrementing counter according to it
return countDig; // Returning the final count
}
you don't need to have a static value counter. It can be easily done as above. Please refer to comments given. Second the error in your code is you only calling the recursion if the LSB is 2 or 6. The recursion should be put outside the if condition in your code. Why are you using num variable. I think it should be n
You don't need statics
This should work (note return c + count(n / 10) line. That's the main recursion here)
int count(int n)
{
int c = 0;
if(n % 10 == 2 || n % 10 == 6)
c = 1;
if(n < 10)
return c;
return c + count(n / 10);
}
If you want to make it with recursion , another procedure you can apply using string manipulation.
PseudoCode:
Function ( int n):
1. Make n as a string. ( Convert Number to string)
2. Collect the first character (char C) of the string and remove the character from the string.
3. Make the main string again as a number n. ( Convert String to Number).
4. Check the character C , which is number 2 or 6 or not, count it with a flag.
5. Enter base case for which the recursion will stop.
6. return the number n , inside the Function (n) for recursion.

Reaching the number 42 by recursion

I am trying to create a bear game where the user enters a number (n), and the program will see if it can reach the number 42 by doing some specified steps. If it can't, then it notifies the user that number can't reach the goal.
These are the rules:
If n is even, then you may give back exactly n/2 bears.
If n is divisible by 3 or 4, then you may multiply the last two digits of n and give back this
many bears.
If n is divisible by 5, then you may give back exactly 42 bears.
Here's an example:
Start with 250 bears
Since 250 is divisible by 5, you may return 42 of the bears, leaving you with 208 bears.
Since 208 is even, you may return half of the bears, leaving you with 104 bears.
Since 104 is even, you may return half of the bears, leaving you with 52 bears.
Since 52 is divisible by 4, you may multiply the last two digits (resulting in 10) and return
these 10 bears. This leaves you with 42 bears.
You have reached the goal!
Here's what I have so far:
#include <iostream>
using namespace std;
bool bears(int n);
int main(){
int number;
do{
cout<<"enter the amount of bears (press 0 to stop the program): ";
cin>>number;
if (bears(number)){
cout<<"you have reached the goal!"<<endl;
}
else{
cout<<"sorry, you have not reached the goal."<<endl;
}
}while(number != 0);
}
bool bears(int n){
if (n < 42){
return false;
}
else if (n == 42){
return true;
}
else{
if (n % 5 == 0){
return bears(n - 42);
}
else if(n % 2 == 0){
return bears(n / 2);
}
else if(n % 4 == 0|| n % 3 == 0)
{
int one;
int two;
one=n%10;
two=(n%100)/10;
return bears(n - one * two);
}
}
}
My program has the basic rules, but when I type in 250 bears it says it can't reach the goal. I understand what's happening in the code and why it can't reach the specified goal, but how do I make it universal so it'll work not just for the number 250, but for other numbers like: 84.
#Corristo's answer is good, but a similar depth first search algorithm can be used with minimal changes to your code. I've removed the redundant ifs and elses (since we're returning in every condition).
What this function does is instead of using a greedy approach like your solution does, it tests all cases till it finds an answer. Your code tests the second condition only if the first condition (divisibility by 5) is not satisfied, and so on.
bool bears(int n){
if (n < 42)
return false;
if (n == 42)
return true;
// Moves on if condition isn't satisfied
if ((n % 5 == 0) && bears(n - 42)) return true;
if ((n % 2 == 0) && bears(n / 2)) return true;
if(n % 4 == 0|| n % 3 == 0)
{
int one;
int two;
one=n%10;
two=(n%100)/10;
return one * two != 0 && bears(n - one * two);
}
return false;
}
You can try optimizing it further by using a cache (std::map) where you store the results and return the stored result if you have computed it before, but it'll only help in very few cases.
Since we don't have any a priori knowledge about which rule we need to choose for a particular number, the easiest way is to try all of them by exploring the entire state space. You can think of it as a reachability problem in an implicitly given graph.
One way to solve such a reachability problem is by using breath-first or depth-first search, which can be implemented recursively.
For your game this can be done by modifying your bears function to take a std::vector of integers for which it checks if it contains at least one number from which 42 can be reached.
With a depth-first search it might look as follows:
bool bears(std::vector<int> ns) {
// first remove all numbers < 42 since the goal cannot be reached from them
ns.erase(std::remove_if(std::begin(ns), std::end(ns),
[] (auto const& n) { return n < 42; }),
std::end(ns));
if (ns.empty()) {
return false;
} else if (std::any_of(std::cbegin(ns),
std::cend(ns),
[] (auto const& n) { return n == 42; })) {
return true;
} else {
auto possible_number_of_bears = std::vector<std::vector<int>>{};
std::transform(std::cbegin(ns),
std::cend(ns),
std::back_inserter(possible_number_of_bears),
[] (auto const& n) {
auto after_possible_rules = std::vector<int>{};
if (n % 5 == 0) {
after_possible_rules.emplace_back(n - 42);
}
if (n % 2 == 0) {
after_possible_rules.emplace_back(n / 2);
}
if (n % 4 == 0 || n % 3 == 0) {
int one;
int two;
one = n % 10;
two = (n % 100) / 10;
// avoid infinite recursion by only adding
// the new number if it is different from n
if (one * two != 0) {
after_possible_rules.emplace_back(n - one * two);
}
}
return after_possible_rules; });
return std::any_of(std::cbegin(possible_number_of_bears),
std::cend(possible_number_of_bears),
bears);
}
}
Now you only need to adjust the calling code to
if (bears({number})) {
std::cout << "you have reached the goal!" << std::endl;
} else {
std::cout << "sorry, you have not reached the goal." << std::endl;
}
and modify the forward declaration of bears accordingly.

Difficulties in understanding this recursion

I don't get this recursion exercise in C++. Here it is:
int fatt(int x){
int s=1; // here. since 's' will always be 1 shouldn't i get 1 as an output???
if(x>1) { s = x*fatt(x-1); }
return s;
}
int main()
{
int n;
cout << "Type a number: ";
cin >> n;
if (n < 0) { cout << "Error" << endl; }
if (n <=1) { cout << "Factorial: 1" << endl; }
else { cout << "Factorial: " << fatt(n) << endl; }
}
If I put s=0 it returns me as an output always 0, if I put 2 it doubles the result O.o I don't get how it works. I understand that x is always getting diminished until reaches 2 and the returns the result but everytime the function is called shouldn't 's' be given the value of 1???
Say you call the function with the parameter value 3: It would look like this:
int fatt(3) {
int s = 1;
if (3 > 1) s = 3 * fatt(3 - 1);
return s;
}
So s is the result of the calulation 3 * fatt(2) and the result of fatt(2) is:
int fatt(2) {
int s = 1;
if (2 > 1) s = 2 * fatt(2 - 1);
return s;
}
So s is the result of the calculations 2 * fatt(1) and the result of fatt(1) is:
int fatt(1) {
int s = 1;
if (1 > 1) s = 1 * fatt(1 - 1); // False so this is never executed.
return s;
}
The result of fatt(1) is 1. So that is what we return to the call of fatt(2) which then translates to:
s = 2 * 1;
Which gives the result 2 which is then returned to the call of fatt(3) which then gives:
s = 3 * 2;
Which gives the result 6.
Remember that the local variable s is pushed on the stack each time the function is executed. So it is not the same variable.
If you initiated s to 2, then the first line would read: s = 2 * 2; and the rest of the function would give double the value in result. Since s is really a factor that you end up multiplying with, in your factorial:
So the sequence: 3 * 2 * 1 becomes 3 * 2 * 2.
The variable s is local to the given instantiation of the function fatt. As the function recursively calls itself, every invocation gets its own new copy of s. This is initialised to 1, but doesn't affect all the previous s instances lower down in the stack. Each one of those is then assigned to the result of the fatt invocation mediately after it multiplied by its local copy of x.
's' should be 1 but it gets assigned and then changes the value it holds upon the completion of a function.
Recursions can be a bit hard to understand at first but once you do, it's beautiful.
I suggest you use a pen and paper.
1) Let x = 3;
int fatt(3) {
int s = 1;
if (3 > 1) s = 3 * fatt(3 - 1);
return s;}
2) In the function 3>1 = true so it gets passed on again but this time as (3-1) i.e 2
Note: function isn't done executing
3) Now x = 2
int fatt(2) {
int s = 1;
if (2 > 1) s = 2 * fatt(2 - 1);
return s;}
4) Repeat step 2) (2-1) i.e 1
5) Since x IS NOT > 1 in the 3rd function call this results in the returning of s
s = 1;
return s;
So...
Starting at the 2rd function call:
s = x * fatt(x-1);
s = 2 * 1;
return s;
Repeat this again for the first call)
s = x * fatt(x-1);
s = 3 * 2;
return s;
Think of it like a stack of functions
1st stack ------- calls stack 2 and waits
2nd stack ---------- calls stack 3 and waits
1st stack ---------- waiting
Finally...
3rd stack ---------- condition not met return
2nd stack ---------- condition done return
1st stack --------- condition done return
Hope that helps