Any better way of implementing this recusively?

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: May 2004
Posts: 3
Reputation: AmericanD is an unknown quantity at this point 
Solved Threads: 0
AmericanD AmericanD is offline Offline
Newbie Poster

Any better way of implementing this recusively?

 
0
  #1
May 3rd, 2004
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.

  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];
}
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC