Search code examples
calgorithmknuth

Knuth's Art of Programming Third Edition and the Euclidean algorithm example


I just started reading volume 1 of Knuth's art of programming and got to the section on page 4 where he describes the Euclidean algorithm. He states the steps to find the greatest common divisor of two numbers. You can read more about it here https://en.wikipedia.org/wiki/Euclidean_algorithm

He steps through an example of finding the GCD of 199 and 544 which he states 17 as the answer. I quickly implemented the algorithm just to follow along but was getting the answer 1. Using my calculator I also get the answer 1.

my code is.

#import <math.h>
#import <stdio.h>

double GreatestComminDivisor(int m, int n) {

    double r = fmod(m, n);
    if (m < n) {
        int temp = n;
        n = m;
        m = temp;
    }

    while (r != 0) {
        r = fmod(m, n);

        if (r == 0) {
            return n;
        }

        m = n;
        n = r;
    }

    return n;
}

int main(int argc, char const *argv[]) {

  int m = 199;
  int n = 544;
  double answer = GreatestComminDivisor(m, n);

  printf("GCD of %i and %i is %f \n", m, n, answer);

  return 0;
}

Am I missing something in his example of did he get the answer wrong. I have tried to look up the errata for the third edition of the book and not getting any results. Just want to make sure I'm not going mad.


Solution

  • Here's an example of a GCD function

    int gcd( int a, int b )
    {
        if ( b == 0 )
            return( a );
        else
            return( gcd( b, a % b ) );
    }
    

    And the numbers are 119 and 544.