- /* A little algorithmic adventure in math,
- // Greatest common denominator/divisor.
- //
- // Note that this does not attempt to properly handle negative numbers
- // beyond what strtoul() does.
- // (When did strtoul() start "casting" negatives to positive?)
- //
- // If anyone hassles me about Intellectual Property on this,
- // I'll hit them over the head with a copy of Euclid, and again with a copy of Knuth.
- // Joel Rees, Amagasaki, March 2015
- */
-
-
- #include <stdio.h>
- #include <stdlib.h>
-
-
- long gcd( long numA, long numB )
- {
- long temp;
-
- while ( numA != numB )
- {
- if ( numA < numB )
- {
- temp = numA;
- numA = numB;
- numB = temp;
- }
- numA -= numB;
- }
- return numA;
- }
-
-
- int main( int argc, char * argv[] )
- {
- long n1, n2;
- char * parseP;
- long divisor;
-
- if ( argc != 3 )
- { printf( "usage: %s <numA> <numB>\n",
- argv[ 0 ] );
- puts( "\tto calculate the greatest common divisor\n\tof two unsigned numbers." );
- return EXIT_FAILURE;
- }
-
- n1 = strtoul( argv[ 1 ], &parseP, 0 );
- if ( parseP > argv[ 1 ] )
- {
- n2 = strtoul( argv[ 2 ], &parseP, 0 );
- if ( parseP > argv[ 2 ] )
- {
- divisor = gcd( n1, n2 );
- printf( "greatest common divisor: %ld\n", divisor );
- printf( "%ld/%ld => %ld/%ld\n", n1, n2, n1 / divisor, n2 / divisor );
- return EXIT_SUCCESS;
- }
- else
- {
- printf( "%s is not an unsigned number I can recognize.\n", argv[ 2 ] );
- }
- }
- else
- {
- printf( "%s is not an unsigned number I can recognize.\n", argv[ 1 ] );
- }
- return EXIT_FAILURE;
- }