c++ Recursion addition, 4*x - c++

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));
}

Related

Recursive c++ function

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.

Is Coin Change Algorithm That Output All Combinations Still Solvable By DP?

For example, total amount should be 5 and I have coins with values of 1 and 2. Then there are 3 ways of combinations:
1 1 1 1 1
1 1 1 2
1 2 2
I've seen some posts about how to calculate total number of combinations with dynamic programming or with recursion, but I want to output all the combinations like my example above. I've come up with a recursive solution below.
It's basically a backtracking algorithm, I start with the smallest coins first and try to get to the total amount, then I remove some coins and try using second smallest coins ... You can run my code below in http://cpp.sh/
The total amount is 10 and the available coin values are 1, 2, 5 in my code.
#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <cmath>
#include <vector>
using namespace std;
vector<vector<int>> res;
vector<int> values;
int total = 0;
void helper(vector<int>& curCoins, int current, int i){
int old = current;
if(i==values.size())
return;
int val = values[i];
while(current<total){
current += val;
curCoins.push_back(val);
}
if(current==total){
res.push_back(curCoins);
}
while (current>old) {
current -= val;
curCoins.pop_back();
if (current>=0) {
helper(curCoins, current, i+1);
}
}
}
int main(int argc, const char * argv[]) {
total = 10;
values = {1,2,5};
vector<int> chosenCoins;
helper(chosenCoins, 0, 0);
cout<<"number of combinations: "<<res.size()<<endl;
for (int i=0; i<res.size(); i++) {
for (int j=0; j<res[i].size(); j++) {
if(j!=0)
cout<<" ";
cout<<res[i][j];
}
cout<<endl;
}
return 0;
}
Is there a better solution to output all the combinations for this problem? Dynamic programming?
EDIT:
My question is is this problem solvable using dynamic programming?
Thanks for the help. I've implemented the DP version here: Coin Change DP Algorithm Print All Combinations
A DP solution:
We have
{solutions(n)} = Union ({solutions(n - 1) + coin1},
{solutions(n - 2) + coin2},
{solutions(n - 5) + coin5})
So in code:
using combi_set = std::set<std::array<int, 3u>>;
void append(combi_set& res, const combi_set& prev, const std::array<int, 3u>& values)
{
for (const auto& p : prev) {
res.insert({{{p[0] + values[0], p[1] + values[1], p[2] + values[2]}}});
}
}
combi_set computeCombi(int total)
{
std::vector<combi_set> combis(total + 1);
combis[0].insert({{{0, 0, 0}}});
for (int i = 1; i <= total; ++i) {
append(combis[i], combis[i - 1], {{1, 0, 0}});
if (i - 2 >= 0) { append(combis[i], combis[i - 2], {{0, 1, 0}}); }
if (i - 5 >= 0) { append(combis[i], combis[i - 5], {{0, 0, 1}}); }
}
return combis[total];
}
Live Demo.
Exhaustive search is unlikely to be 'better' with dynamic programming, but here's a possible solution:
Start with a 2d array of combination strings, arr[value][index] where value is the total worth of the coins. Let X be target value;
starting from arr[0][0] = "";
for each coin denomination n, from i = 0 to X-n you copy all the strings from arr[i] to arr[i+n] and append n to each of the strings.
for example with n=5 you would end up with
arr[0][0] = "", arr[5][0] = "5" and arr[10][0] = "5 5"
Hope that made sense. Typical DP would just count instead of having strings (you can also replace the strings with int vector to keep count instead)
Assume that you have K the total size of the output your are expecting (the total number of coins in all the combinations). Obviously you can not have a solution that runs faster than O(K), if you actually need to output all them. As K can be very large, this will be a very long running time, and in the worst case you will get little profit from the dynamic programming.
However, you still can do better than your straightforward recursive solution. Namely, you can have a solution running in O(N*S+K), where N is the number of coins you have and S is the total sum. This will not be better than straightforward solution for the worst possible K, but if K is not so big, you will get it running faster than your recursive solution.
This O(N*S+K) solution can be relatively simply coded. First you run the standard DP solution to find out for each sum current and each i whether the sum current can be composed of first i coin types. You do not yet calculate all the solutions, you just find out whether at least one solution exists for each current and i. Then, you write a recursive function similar to what you have already written, but before you try each combination, you check using you DP table whether it is worth trying, that is, whether at least one solution exists. Something like:
void helper(vector<int>& curCoins, int current, int i){
if (!solutionExists[current, i]) return;
// then your code goes
this way each branch of the recursion tree will finish in finding a solution, and therefore the total recursion tree size will be O(K), and the total running time will be O(N*S+K).
Note also that all this is worth only if you really need to output all the combinations. If you need to do something else with the combinations you get, it is very probable that you do not actually need all the combinations and you may adapt the DP solution for that. For example, if you want to print only m-th of all solutions, this can be done in O(N*S).
You just need to make two passes over the data structure (a hash table will work well as long as you've got a relatively small number of coins).
The first one finds all unique sums less than the desired total (actually you could stop perhaps at 1/2 the desired total) and records the simplest way (least additions required) to obtain that sum. This is essentially the same as the DP.
The second pass then goes starts at the desired total and works its way backwards through the data to output all ways that the total can be generated.
This ends up being a two stage approach of what Petr is suggesting.
The actual amount of non distinct valid combinations for amounts {1, 2, 5} and N = 10 is 128, using a pure recursive exhaustive technique (Code below). My question is can an exhaustive search be improved with memoization/dynamic programming. If so, how can I modify the algorithm below to incorporate such techniques.
public class Recursive {
static int[] combo = new int[100];
public static void main(String argv[]) {
int n = 10;
int[] amounts = {1, 2, 5};
ways(n, amounts, combo, 0, 0, 0);
}
public static void ways(int n, int[] amounts, int[] combo, int startIndex, int sum, int index) {
if(sum == n) {
printArray(combo, index);
}
if(sum > n) {
return;
}
for(int i=0;i<amounts.length;i++) {
sum = sum + amounts[i];
combo[index] = amounts[i];
ways(n, amounts, combo, startIndex, sum, index + 1);
sum = sum - amounts[i];
}
}
public static void printArray(int[] combo, int index) {
for(int i=0;i < index; i++) {
System.out.print(combo[i] + " ");
}
System.out.println();
}
}

Sum the odd positioned and the even positioned integers in an array

What is the most elegant way to sum 'each number on odd position' with 'each number on even position multiplied by 3'? I must obide this prototype
int computeCheckSum(const int* d)
My first try was to use this but my idea was flawed. I can't find a way to tell which element is even this way.
int sum=0;
for_each(d,
d+11,
[&sum](const int& i){sum+=(i%2==1)?3*i:i;}
);
example
1 2 3 4 5
1+2*3+3+4*3+5=27
I can't find a way to tell which element is even this way.
If you insist on using for_each (there's no reason to do that here), then you track the index separately:
int computeCheckSum(const int* d, int count)
{
int sum=0;
int pos=1;
std::for_each(d, d+count,
[&sum,&pos](const int& value) { sum += pos++ % 2 ? value : value * 3; } );
return sum;
}
Note I added a count parameter, so the function can work on arrays of any length. If you're feeling really perverse, you can remove that parameter and go back to hardcoding the length so the function only works arrays with 12 elements. But if you hope to be good at this some day, doing that should make you feel gross.
These things rarely become very "elegant" in C++ (it seems C++ is asymptotically approaching Perl on the "line noise" index) but since accumulate is a left fold, you can pass the index "along the fold":
int sum = std::accumulate(d,
d + 11,
std::make_pair(0,0), // (index, result)
[](std::pair<int, int> r, int x) {
r.second += r.first % 2 ? x : 3 * x;
r.first++;
return r;
}).second;
You were right. As Mud said, it was just a terrible function design. This is what I needed.
int computeCheckSum(){
int sum = 0;
bool multiplyBy3 = false;
for (auto i : m_digits){
sum += multiplyBy3 ? 3*i : i;
multiplyBy3 = !multiplyBy3;
}
return sum;
}
Mud's solution is correct using my flawed design. A simple for loop would probably be even a better solution, as everyone said.

Best program for Permutation nPr of large numbers

I am new to programming and was stuck at the permutation part. I have code which works for combination of large numbers which is stored in matrix but i am not able to find what should i change in that to get the result.
I tried the recursive method for permutations but could not achieve fast results.
This is the code which i got for combination what should be the change in condition which i should do here to get permutations?
void combination()
{
int i,j;
for(i=0;i<100;i++)
{
nCr[i][0]=1;
nCr[i][i]=1;
}
for(i=1;i<100;i++)
for(j=1;j<100;j++)
if (i!=j)
{
nCr[i][j] = (nCr[i-1][j] + nCr[i-1][j-1]);
}
}
A recurrence rule for permutations can be easily derived from the definition:
nPk = n*(n-1)*(n-2)* ... * (n-k+1) = n * (n-1)P(k-1)
Converted to code:
for(i=0;i<100;i++)
{
nPr[i][0]=1;
}
for(i=1;i<100;i++)
for(j=1;j<100;j++)
if (i!=j)
{
nPr[i][j] = i * nPr[i-1][j-1];
}
Note that the number of permutations grows fast and overflows the storage available for int: 13P11 for example is already out of range with signed 32bit integers.
well you can use the following pseudo-code for computing permutation and combination given that mod is always a very large prime number.
for permutation nPr
func permutation(r,n,mod):
q=factorial(n) // you should precompute them and saved in an array for a better execution time
r=(factorial(r))%mod
return (q*math.pow(r,mod-2))%mod
for combination nCr
func combination(r,n,mod):
q=factorial(n)
r=(factorial(r)*factorial(n-r))%mod
return (q*math.pow(r,mod-2))%mod
your should precompute factorials , for a decent execution time.
fact[100000]
fact[0]=fact[1]=1
func factorial_compute():
for x from 2 to 100000:
fact[x]=(x*fact[x-1])%mod
hence your factorial function will be
func factorial(x):
return(fact[x])
for reference on mathematics for this : http://mathworld.wolfram.com/ModularInverse.html
Actually, I know where the problem raised
At the point where we multiply , there is the actual problem ,when numbers get multiplied and get bigger and bigger.
this code is tested and is giving the correct result.
#include <bits/stdc++.h>
using namespace std;
#define mod 72057594037927936 // 2^56 (17 digits)
// #define mod 18446744073709551616 // 2^64 (20 digits) Not supported
long long int prod_uint64(long long int x, long long int y)
{
return x * y % mod;
}
int main()
{
long long int n=14, s = 1;
while (n != 1)
{
s = prod_uint64(s , n) ;
n--;
}
}

Recursion counter inside a C++ function

Doing an assignment on recursive functions at the moment.
Was asked to do a Fibonacci program and did so with out much issue.
But I'm need to make a counter for it, and here is where I'm getting stuck.
I've got this function
int fibonacci(int n)
{
if( n == 0 )
{
//my fibonacci code
}
else if( n == 1 )
{
//my fibonacci code
}
else
{
//my fibonacci code
}
}
So how to I add a counter to this? Ever time I add a counter it returns the wrong number.
Edit Just to clarify, my function works fine generating the Fibonacci numbers. I just wanted to add a counter inside the function so I can see how many times it is being called every time I want it to generate a Fibonacci number.
I have since tried one of the methods below where I initialise a counter in the main function then increment it in the recursion but don't know if the number is correct. For example it is saying that I'm calling the function 609 times if my Fibonacci number is 610, is that correct?
I'm guessing you just need the count for demonstration purposes, right?
Counting the calls should be easily achievable by passing in a counter variable by reference, and increasing it once at the beginning of each call, like so:
#include <iostream>
// ...
int fibonacci(int n, int &count)
{
++count;
// other code ...
// and every time you call fibonacci recursively,
// simply pass in the same reference, like so:
if (...) {
fibonacci (new_n, count);
}
}
int main(int argc, char** argv)
{
// call it with an int variable initialized to 0:
int fibCnt = 0;
fibonacci(10, fibCnt);
std::cout << "Function was called "<<fibCnt<<" times"<<std::endl;
}
You don't need any counters. Your code is already almost there
int fibonacci(int n)
{
if( n == 0 )
{
return f_0
}
else if( n == 1 )
{
return f_1
}
else
{
return f_n using recursion
}
}
As the Fibonacci numbers are defined via recursion, the last case is obvious. The other two are needed only to close the recursion relations, i.e. to avoid the last case to result in an infinite loop.
Complete the code first. I give you the recursion equations:
fib(0) = *deleted*
fib(1) = *deleted*
fib(n) = *deleted*
Your counter (which you should still specify in your question) can be usually implemented by a global variable defined outside the function but be changed within the function.
Referring to the question's edit:
Your number is not good. To not spoil your task more, I give you the answer in Erlang, so you still have some work left to figure out how to get it right in your C++ task. :-)
-module(fib).
-export([f/1]).
%% returns a tupel { fibonacci value, number function calls }
f(0) -> {0, 1};
f(1) -> {1, 1};
f(X) ->
{F1, C1} = f(X - 1), %% decompose tuple
{F2, C2} = f(X - 2),
{F1 + F2, C1 + C2}. %% return value
Running this from a shell gives:
Eshell V5.10.1 (abort with ^G)
1> c("q:/doc/erlang/fib", [{outdir, "q:/doc/erlang/"}]).
{ok,fib}
2> fib:f(0).
{0,1}
3> fib:f(1).
{1,1}
4> fib:f(2).
{1,2}
5> fib:f(3).
{2,3}
6> fib:f(4).
{3,5}
7> fib:f(5).
{5,8}
8> fib:f(6).
{8,13}
9> fib:f(7).
{13,21}
10> fib:f(15).
{610,987}
11>
Thus I get 987 function calls to get at the F(15) = 610 value.
The interesting bit here is, in the comments we talked about the proper start conditions for the Fibonacci recursion F (the situation is similar to differential equations, a different start point gets you on a different trajectory / solution).
I got it wrong with F(0) = 1 and F(1) = 1, while #WhozCraig correctly pointed out it should be F(0) = 0 and F(1) = 1.
If you look at the Erlang code above you see that the calculation of the series which yields the number of function calls is a Fibonacci type one as well (adding the last two members of the series), but that one is the one with the start values 1 and 1! :-)
Using struct could be the answer.
struct factorial
{
factorial() : counter(0)
{}
uint64_t foo(uint64_t x) {
++counter;
if(x < 2)
return 1;
else
return x * foo(x - 1);
}
template <class T>
T operator()(const T& x) {
return foo(x);
}
uint64_t counter;
} factorial;
In this case, foo is the factorial function. but doesn't have that name, because the usage of the struct will be.
// output and calls
struct factorial foo;
std::cout << foo(5) << "\n";
std::cout << foo.counter << "\n";
// output
std::cout << factorial(5) << "\n";