Recursive c++ function - c++

I am trying to create a recursive function as follows.
The function takes a counter k and as long that the counter is larger than zero I would like to call it recursively so that in the end I end up with something like this:
result = 2(2(2n+1)+1)+1
where the last n (when k=0) should be zero.
int pass(int k, int n)
{
if(k==0)
{
n = 0;
}
else
{
k--;
return pass(k, 2*n+1);
}
}
Can someone give me a hint as on how to do it?

Change
n = 0;
To
return n;
To return the result.
The rest of the code is fine

Currently the behaviour of your code is undefined since you don't explicitly return a value on all control paths.
Your code can simplify down to:
int pass(int k, int n)
{
return k ? 2 * pass(k - 1, n) + 1 : 1;
}
Here I've used the ternary conditional operator. 2 * pass(k - 1, n) + 1 is returned if k is non-zero, 1 is returned otherwise.
Take care not to overflow your int in this case. Note that the maximum size of an int can be as small as 32767. Consider using a long type instead.
Also, note that recursion is not normally a good way of solving O(n) type problems; you could get errors at runtime due to a function call stack limit being exceeded: consider folding to a loop instead.

Related

How does memoization help here?

I just solved the subset sum problem:
Given an integer array nums of size N. You are also given an integer B, you need to find whether there exists a subset in nums whose sum is B. If there exist a subset then return 1 else return 0.
Constraints are: 1 <= N <= 100; 1 <= nums[i] <= 100; 1 <= B <= 10^5;
The way I solved this problem is as below (0/1 knapsack):
vector<int> n;
int t;
unordered_map<string, long long> m;
int helper(int i, int sum) {
if(i>=n.size()) return sum==t;
string str=to_string(i)+"-"+to_string(sum);
if(m.count(str)) return m[str];
int val=helper(i+1, sum+n[i]);
val=max(val, helper(i+1, sum));
return m[str]=val;
}
int Solution::solve(vector<int> &nums, int B) {
n=nums;
t=B;
m.clear();
return helper(0,0);
}
This gets "Accepted". However, note that all the values in nums are positive; so IMO sum will only remain the same/go on increasing. i goes on increasing, too. So, we will never encounter a value previously stored in the memoization table.
But, if I remove memoization, it results in Wrong Answer for some large test case. What am I missing? Will any recursive call ever encounter a previous state?
You call helper twice, the second time with the lower sum than the first. Therefore a later call to helper could indeed have the same sum as an earlier call.
#user3386109 already gave a concrete set of num that demonstrates this. As for how often, consider the case where nums = [1, 1, ..., 1] 100 times. Then without memoization you'll call helper(100, 50) 100 choose 50 = 100,891,344,545,564,193,334,812,497,256 times. Over 100 octillion calls..takes a while.

c++ Recursion addition, 4*x

I have been trying to understand how to work on a function that returns the sum of a number like this: 1+2+3+4...4n by using recursion
I tried different cases without success and I am wondering if there is any mathematical way to solve it and translate it into code. I know that if I were this function:
int MyFunction(int x)
{
if (x==0)
return 0;
else{
return x+MyFunction(x-1);
}
}
and I used x=3 it would return 1+2+3 which is equal to 6 but in my case, I want to do something similar but up to 4 times the number. For example if x=1 it will return 1+2+3+4 since 4(1)=4. Then what returns is the addition of those numbers which is equal to 10
I tried thinking about simply converting the x to 4*x
int MyFunction(int x)
{
if (x==0)
return 0;
else{
return 4*x+MyFunction(x-1);
}
}
of course this didn't work, I also tried thinking that since everything was the same but by a factor of 4 thus MyFunction(4(x-1)) but obviously I am not thinking of this correctly. I wanted suggestions at least to understand the math behind it and how to relate it to code
nonrecursive solution
The sum of the members of a finite arithmetic progression is called an arithmetic series. For example, consider the sum:
1 + 2 + 3 + ... 4n-1 + 4n
This sum can be found quickly by taking the number of terms being added (here 4n), multiplying by the sum of the first and last number in the progression (here 1 + 4n = 4n+1), and dividing by 2.
The formula you are looking for is:
sum = 2n(4n+1)
A possible implementation can be:
int MyFunction(int n)
{
assert(n>0);
return 2*n*(4*n+1);
}
note: we do not checked a possible overflow
recursive solution
int recursive_sum(int k)
{
return (k>0) ? k+recursive_sum(k-1) : 0;
}
int recursive_MyFunction(int n)
{
assert(n>0);
return recursive_sum(4*n);
}
Check that both approaches give the same result
#include <cassert>
int MyFunction(int n) { ... as before ...}
int recursive_MyFunction(int n) { ... as before ...}
int main()
{
int n = 10; // whatever you want
assert(recursive_MyFunction(n)==MyFunction(n));
}

Creating a Recursive Function for Number Sequence

I know this is basic CS knowledge, but I still can't grasp the idea of doing a recursive function over a for loop. I'm still confused on the idea of recursion especially with numbers. Lets say there's a numerical sequence 3, 11, 27, 59, 123.... I know how to figure out the mathematical recursive sequence which is just An = An-1 + (8*(n-1)), but don't really know how to put this into a C++ recursive function.
Can someone outline the creation of a recursive function for the above numerical sequence?
Recursive functions have two "parts", the base case and the recursion. The base case is when your function stops recursing (and starts unwinding the call stack). Without the base the function just keeps calling itself until the stack overflow happens and the program is terminated by the OS.
The recursive part takes the initial problem (in your case finding the ith number in a sequence) and shrinks it. This happens until the base case is hit. So for finding the ith number in a sequence, let's say the 4th, you start looking for the 4th number, but that depends on the 3rd, which depends on the 2nd which depends on the first. The initial recursion shrinks the problem from the 4th number to the 3rd.
Here's a stab (not at all tested) at a recursive function for your sequence.
int recursive(int i) {
// This is your base case, it prevents infinite recursion.
if (i == 0) return 0; // Or whatever you base value is
else {
int sum = recursive(i-1) + 8 * (i-1);
return sum;
}
}
Lots of times a recursive function can be done with a loop. However there are functions which require recursion. For instance, Ackermann's Function. A really good video on Computerphile
Basic recursive implementation of said function (proper values for your sequence are 3, 11, 27, 51, 83, 123, … btw):
int seq(int n)
{
if (n <= 1)
return 3;
else
return seq(n-1) + 8 * (n-1);
}
However, this implementation is not tail-recursive (therefore it will use stack, while iterative implementation would not). We can write tail-recursive version by introducing accumulator parameter:
int seq_r(int n, int acc)
{
if (n <= 1)
return acc;
else
return seq_r(n-1, acc + 8 * (n-1));
}
int seq(int n)
{
return seq_r(n, 3);
}
Or, same implementation but with seq_r hidden inside your function using lambda expressions:
#include <functional>
int seq(int n)
{
std::function<int(int, int)> seq_r = [&] (int n, int acc) -> int {
if (n <= 1)
return acc;
else
return seq_r(n-1, acc + 8 * (n-1));
};
return seq_r(n, 3);
}
If your sequence function is defined as: A[n] = A[n-1] + 8*(n-1) then you need two things. 1) A structure to hold the sequence of numbers, and 2) a function or loop to produce those numbers. For the structure I will use a std::vector and the loop or function can be used as below:
Loop
#include <vector>
int main()
{
std::vector<int> storage;
// Seed the storage with a number since the sequence looks back.
storage.push_back(3);
// Define the maximum number count.
int maxNum = 5;
// Create the sequence by starting from n=1 since there are [n-1] terms.
for(int n = 1; n <= maxNum; n++)
storage.push_back(storage[n - 1] + 8*(n - 1));
return 0;
}
Function
#include <vector>
std::vector<int> storage;
void DoSequence(int maxNum, int n = 0)
{
// Check the limit.
if(n > maxNum)
return;
// Check seeding condition if adding the first element,
// otherwise run the equation.
if(n == 0)
storage.push_back(3);
else
storage.push_back(storage[n - 1] + 8*(n-1));
// Call the same function.
DoSequence(maxNum, n + 1);
}
int main()
{
// Call the recursive function with upper limit (n=5).
DoSequence(5);
return 0;
}
There are other ways to implement the details such as how storage is declared or handled but that is personal preference. Note: I did not test this code but hopefully you get the idea. In short, once you have your sequence function defined then create a loop or program function to generate the numbers.

Recursively finding a negative in an array of doubles

My homework assignment requires me to go through an array of doubles and return true or false depending on whether or not it contains a negative number or not. The catch is that I have to use a recursive function and I can't use loops. I also can't use access any functions or variables outside of the function I am given.
The function takes two parameters: the array, and the number of elements to be inspected.
I'm having trouble making it stop recursing once it has inspected the specified number of elements.
//what I have so far
bool anyNegative(const double a[], int n)
{
if(n <= 0)
return false;
if(*a < 0)
return true;
anyNegative(a + 1, n);
}
First, I thought of using counter, but that doesn't work since it gets reset every time the function recurses.
I also tried to compare pointer indexes with
if(currentElement == &a[n])
where currentElement is a pointer to the first element of array a.
However, I THINK the reason my program didn't work when I did that is because "a" is set to a new value every time the function is recursed so that &a[n] will always be n elements ahead of currentElement.
I'm stuck and if someone could give me a hint, that would be great.
Decrease n, since the array you pass is smaller
anyNegative(a + 1, n - 1);
You need to decrease n, and also return the value of recursive call.
return anyNegative(a + 1, n - 1);
You are missing two things, first you are not decrementing value of n so that terminating condition can be reached. Secondly you are not returning the result of sub-executions to the upper level.
Here is the modified code:
//what I have so far
bool anyNegative(const double a[], int n)
{
if(n <= 0)
return false;
if(*a < 0)
return true;
return anyNegative(a + 1, n - 1);
}
Size of an array can not be negative. So that do not do such a superfluous check as
if(n <= 0)
return false;
it is better to define the second parameter as having type size_t.
Your function has undefined behaviour because it returns nothing when the control will achieve statement
anyNegative(a + 1, n);
and moreover instead of the call above must be
anyNegative(a + 1, n -1);
I would write the function the following way
bool anyNegative( const double a[], size_t n )
{
if ( n == 0 ) return false;
return ( *a < 0 ? true : anyNegative( a + 1, n - 1 ) );
}

Horner's Rule C/C++ Using Recursion

I learned about Horner's Rule here for the first time:
Horner's rule in C++
Since I am learning about recursion ATM, I was wondering if it is possible to implement this algorithm using recursion ?
int HornerR( int a[], int n, int x, int index )
{
if (index==n) return a[n];
else
return x*HornerR(a,n ,x,index+1) + a[index];
}
I think it's only possible with a fourth parameter.
You can do it with pointer arithmetic:
Base Case at the end of array (check n) return constant parameter
Recursive Case return current cell added to variable multiplied recursive call
Recursive Call move the array to next cell and update the counter (n)
Basically this lets you calculate the index variable by moving the array to the next position and sending that (and always using the first cell) instead of sending the whole array every time
You can implement the function as follows with 3 arguments in function, provided, the array pi contains the coefficients from highest degree to 0 from index 0 to degree+1. Ex for 3x^2 + 2x^1 + 1 => pi[3] = { 3,2,1}
int compute_by_horner(int *pi, int degree, int x)
{
int i, j;
if (degree == 0)
{
return pi[0];
}
return compute_by_horner(pi, degree-1, x) * x + pi[degree];
}
Rather than passing an index, think of a as a pointer (since it is). Along with that, you'll want to decrement n, and keep track of whether it's been reduced to zero yet, rather than keeping track of whether index==n.