How to find the greatest common divisor of two numbers in C language? The following are solved in three ways.
Method One: Poor lifting method.
This method is less efficient when you compare the size of two numbers, then find the smaller number T, and finally determine why the value of T is divisible by two numbers at a time.
The code is as follows:
#include <stdio.h>int main () {int num1,num2,temp,i; scanf ("%d%d", &num1,&num2); if (num1>num2) {temp=num1; num1=num2; Num2=temp; }/* assigns a smaller value to num1*/for (i=num1;i>0;i--) {if (num1%i==0&&num2%i==0)/*/Two numbers are all divisible by I, which is greatest common divisor */ printf ("%d", I); }return 0;}
Method Two: Tossing and subtracting.
The subtraction is to use the larger number minus the smaller number, and then compare the size of the meiosis and the difference, with the larger number minus the smaller number, so continuously cycle, until the two number is subtracted to 0 stop, then greatest common divisor to find out.
The code is as follows:
#include <stdio.h>int main () {int A, B; scanf ("%d%d", &a,&b); while (a!=b) {if (a>b) a=a-b;/* compares two number sizes, large numbers decrease the number difference and are assigned to a*/else b=b-a; } printf ("%d", b); return 0;}
Method Three: The method of dividing.
The steps for finding the two-digit greatest common divisor by the Euclidean method are as follows:
First with a small number in addition to a large number , the first remainder;
Then the first remainder is the second remainder , except for a small number;
until the remainder is 0 so far . so The last divisor is the desired greatest common divisor (if the last divisor is 1, So the original two numbers are Inma. )
The code is as follows:
#include <stdio.h>int main () {int num1,num2,temp; scanf ("%d%d", &num1,&num2); /* Do not need to determine the size of two numbers, when Num1<num2, after a single operation, two numbers are automatically exchanged. */while (num2) {temp=num1%num2;/* Greatest common divisor */num1=num2; Num2=temp; } printf ("%d", NUM1); return 0;}
Least common multiple: The required two number multiplied by greatest common divisor is the least common multiple of two numbers.
C language for two numbers in a greatest common divisor