943,578 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 1941
  • C++ RSS
May 3rd, 2004
0

Any better way of implementing this recusively?

Expand Post »
I have a function that does intermediate calculations to a greatest common divisor deal. and here is how its implemented iteratively (see exteuc() function) .

i tried to implement it recursively too, (see exteuc2() function) . feel free to look at it and give me suggestions if i can improve my recursive implementation in any way. even though it works out. i ask because i'm doing c++ programming after a long long time now.

the function takes 2 numbers and 3 arrays of int size 3 each. copyarr just shifts the contents of arrays left by 1. its needed because the array is of size 3 and as i only need 3 values at one time to do calculations on.

C++ Syntax (Toggle Plain Text)
  1. int exteuc2(int num1, int num2, int* x, int* y, int* r)
  2. {
  3. int q, tmp;
  4. r[1] = (num1 * x[1]) + (num2 * y[1]);
  5. tmp = r[1];
  6. if (tmp > 0)
  7. {
  8. q = r[0] / r[1];
  9. x[2] = x[0] - (q * x[1]);
  10. y[2] = y[0] - (q * y[1]);
  11. copyarr(x);
  12. copyarr(y);
  13. copyarr(r);
  14.  
  15.  
  16. exteuc2(num1, num2, x, y, r);
  17. }
  18. return q;
  19. }
  20. int exteuc(int num1, int num2, int* x, int* y, int* r)
  21. {
  22. int q;
  23. while (( r[1] = (num1 * x[1]) + (num2 * y[1])) != 0)
  24. {
  25. q = r[0] / r[1];
  26. x[2] = x[0] - (q * x[1]);
  27. y[2] = y[0] - (q * y[1]);
  28. copyarr(x);
  29. copyarr(y);
  30. copyarr(r);
  31. }
  32. return q;
  33. }


edit : i thought i'ld add copyarr function.

here
void copyarr(int* p)
{
p[0] = p[1];
p[1] = p[2];
}
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
AmericanD is offline Offline
3 posts
since May 2004

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: RTTI typeinfo question
Next Thread in C++ Forum Timeline: Windows Api Tutorial





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC