user7716102
user7716102

Reputation: 55

for loop calculates the same value each time

I am trying to implement a recurrence relation that will return me the kth term. But I am receiving the same output when I change the k value. Here is my code:

int recurrence(int a, int b, int k, int u0, int u1) {
  int u = u0;
  int uu = u1;

  for (int i = 0; i < k; i++)
    uu = a*u1 + b*u0;

  return uu;
}

int recurrence2(int a1, int b1, int k1, int u4, int u5) {
  int u = u4;
  int uu = u5;

  for (int i = 0; i < k1; i++)
    uu = a1*u5 + b1*u4;


  return uu;

}

int main() {
  int h;
  h = recurrence(7, 1, 5, 3, 5 );
  int g;
  g = recurrence2(17, 11, 2, 1, 2);

  cout << "The result is:  " << h;
  cout << "The result is : " << g;
}

Upvotes: 2

Views: 149

Answers (1)

Slava
Slava

Reputation: 44258

You evaluate the same values in expression in the loop, so result would not change regardless how many times you execute it. Looks like this is what you need:

int recurrence(int a, int b, int k, int u0, int u1)
{
    for (int i = 0; i < k; i++) {
        auto tmp = a*u1 + b*u0;
        u0 = u1;
        u1 = tmp;
    }
    return u1;
}

or simpler:

int recurrence(int a, int b, int k, int u0, int u1)
{
    for (int i = 0; i < k; i++) {
        u0 = a*u1 + b*u0;
        std::swap( u1, u0 );
    }
    return u1;
}

second function needs to be changed the same way.

PS you asked how could you maintain state of variables for further invocations, best way is to have class that maintains it:

class Recurrence {
     int m_a;
     int m_b;
     int m_u0;
     int m_u1;

 public:
     Recurrence( int a, int b, int u0, int u1 ) :
         m_a( a ),
         m_b( b ),
         m_u0( u0 ),
         m_u1( u1 )
     {
     }

     int value() const { return m_u1; }

     void interate()
     {
          m_u0 = m_a * m_u1 + m_b * m_u0;
          std::swap( m_u0, m_u1 );
     }

     void interateN( int n )
     {
          for( int i = 0; i < n; ++i ) iterate();
     }
};

int main()
{
     Recurence recurence( 7, 1, 3, 5 );
     recurence.iterateN( 5 );
     int h = recurence.value();
     recurence.iterateN( 5 ); // continue
     ...
}

In reality you may want to have that class more generic - for example use different number of arguments, different types, store them in array etc. This code just to show you the idea.

Upvotes: 1

Related Questions