BillyDean
BillyDean

Reputation: 77

Recursive addition sequence C++

Basically, I need to create a sequence in C++ where if given (5,6) as parameters, the output would be:

5, 11, 18, 26, 35, 45

I have no idea what this is called but it works like this:

5 = 5
11 = 5 + (5 + 1)
18 = 11 + (5 + 2)
26 = 18 + (5 + 3)

and so on and so forth. The number of times this is done is dictated by the second parameter.

I've tried for like 3 days to figure this out but no luck. I usually end up with something like

int recProb(int incrementBy, int counter){
    if (counter == 0){
        return incrementBy;
    }

    cout << incrementBy + recProb(incrementBy + 1, counter - 1) << ", ";
}

or something that resembles the fibonacci sequence recursion solution. If anyone can please point me in the right direction that'd be awesome. Thanks.

(Sorry for the atrocious formatting, I couldn't figure out how to do it properly).

Upvotes: 0

Views: 657

Answers (3)

berbatov
berbatov

Reputation: 11

If you want to:

a) use recursion b) use only 2 parameters (both ints)

I can't see how you can do it. The only way is to hide extra parameters (like original value of num) inside the 2 current parameters and use bitwise operators to extract them later.

    #include <iostream>
using namespace std;

void func(__int32 num, __int32 counter)
{
    if ( (num >> 16) == 0) num += (num << 16) + (1<<16);
    if (counter == 0) return;

    cout << (num & 0xFFFF) << ' ';

    func(num + (1<<16) + (num>>16) , --counter);
}

int main()
{
    func(5, 6);
    cin.get();
}

Upvotes: 1

sray
sray

Reputation: 584

Here is a solution with loops only -

int recProb(int incrementBy, int counter) {
  int i, sum = incrementBy;
  cout << sum << " ";

  for(i=1; i<counter; i++) {
     incrementBy += 1;
     sum += incrementBy;
     cout << sum << " ";
  }
}

Upvotes: 0

molbdnilo
molbdnilo

Reputation: 66451

As far as I can tell, your function is

f(k, 1) = k
f(k, n) = f(k, n-1) + k + (n - 1)

so

int f(int k, int n)
{
    if (n == 1)
    {
        cout << k;
        return k;
    }
    else
    {
       int val = f(k, n-1) + k + (n-1);
       cout << ", " << val;
       return val;
    }
}

could do it.
(Not rigorously tested - only with your example.)

Upvotes: 3

Related Questions