gcd.c 667 B

1234567891011121314151617181920212223
  1. #include "gcd.h"
  2. /*Computes the gcd of two integers, _a and _b.
  3. _a: The first integer of which to compute the gcd.
  4. _b: The second integer of which to compute the gcd.
  5. Return: The non-negative gcd of _a and _b.
  6. If _a and _b are both 0, then 0 is returned, though in reality the
  7. gcd is undefined, as any integer, no matter how large, will divide 0
  8. evenly.*/
  9. int gcd(int _a,int _b){
  10. /*Make both arguments non-negative.
  11. This forces the return value to be non-negative.*/
  12. if(_a<0)_a=-_a;
  13. if(_b<0)_b=-_b;
  14. /*Simply use the Euclidean algorithm.*/
  15. while(_b){
  16. int r;
  17. r=_a%_b;
  18. _a=_b;
  19. _b=r;
  20. }
  21. return _a;
  22. }