Given the value of two integers a, b, r represents the number remaining after the modulo. If a%b==0, directly output b as the greatest common divisor; if a%b!=0, enter the loop, and keep taking the modulo for the remainder until a%b==0.
For example: a = 24,b = 32;
r = a%b =24; (r!=0 enters the loop)
a = 32, b = 24;
r = a%b = 8 ; (r!=0 enters the loop)
a = 24,b = 8;
r = a%b =0; (r==0 to jump out of the loop)
Output greatest common divisor: 8
code show as below:
#include <stdio.h> intmain() { int a = 24; int b = 32; int r = 0; while ((r = a%b) != 0) { a = b; b = r; } printf("The greatest common divisor is: %d\n", b); return 0; }
Supplement: least common multiple * greatest common divisor = product of two numbers
Therefore, the least common multiple can be solved by the above formula.
code show as below:
#include <stdio.h> intmain() { int a = 24; int b = 32; int tmp = a*b; int r = 0; while ((r = a%b) != 0) { a = b; b = r; } printf("The greatest common divisor is: %d\n", b); printf("The least common multiple is: %d\n",tmp/b ); return 0; }