Search code examples
c++number-theory

How to return more than one value from a C++ function?


I am interested if I can return more then one value from a function. For example consider such a function: extended euclidean algorithm. The basic step is described by this Input is nonnegative integers a and b; output is a triplet (d,i,j) such that d=gcd(a,b)=i*a+j*b. Just to clarify my question's goal I will write a short recursive code:

 if (b==0)  return (a,1,0)
      q=a mod b;

let r be such that a=r*b+q;

(d,k,l)=extendedeuclidean(b,q);
  return (d,l,k-l*r); 

How does one return a triplet?


Solution

  • Just create an appropriate data structure holding the three values and return that.

    struct extmod_t {
        int d;
        int i;
        int j
        extmod_t(int d, int i, int j) : d(d), i(i), j(j) { }
    };
    
    …
    
    extmod_t result = extendedeuclidean(b, q);
    return extmod_t(result.d, l, k - l * r);