Home > Article > Backend Development > How to find the greatest common divisor and least common multiple in C language?
Recommended tutorial: "C Video Tutorial"
How to find the greatest common divisor and minimum in C language common multiple?
The method of finding the greatest common divisor and the least common multiple in C language:
Algorithm for finding the greatest common divisor:
There are two integers a and b:
① a%b gets the remainder c
② If c=0, then b is the greatest common divisor of the two numbers
③ If c≠0, then a =b, b=c, then go back and execute ①
For example, the process of finding the greatest common divisor of 27 and 15 is:
27÷15 remainder 1215÷12 remainder 312÷3 remainder 0. Therefore, 3 is the greatest common divisor
#include<stdio.h> int main() /* 辗转相除法求最大公约数 */ { int m, n, a, b, t, c; printf("Input two integer numbers:\n"); scanf("%d%d", &a, &b); m=a; n=b; while(b!=0) /* 余数不为0,继续相除,直到余数为0 */ { c=a%b; a=b; b=c;} printf("The largest common divisor:%d\n", a); printf("The least common multiple:%d\n", m*n/a); }
Find the least common multiple:
#include <stdio.h> int main() { int a,b,A,B; int lol,lpl; printf ("输入两个整数:\n"); scanf ("%d%d",&a,&b); A=a; B=b; if(B) while((A %= B) && (B %= A)); lol = A+B; lpl = a*b/lol; printf ("最小公倍数为:%d\n", lpl); return 0; }
Recommended tutorial: "c#.net Development Graphic Tutorial"
The above is the detailed content of How to find the greatest common divisor and least common multiple in C language?. For more information, please follow other related articles on the PHP Chinese website!