There are many ways to greatest common divisor two numbers, and here are the two algorithms that are highlighted:
The method of dividing and subtracting.
1. The method of dividing.
In two numbers, find the large number, divide the large number by the decimal, get the integer quotient and the remainder, and then continually divide the divisor (the original decimal) by the remainder until there is no remainder.
Then the divisor is greatest common divisor.
So we can use a loop to swap the positions between the divisor, the divisor, and the remainder.
You can also use the Goto statement to cycle through the operation.
Note that the Goto statement is best not to appear multiple times in a program, or the program is likely to be confusing.
Here is a program code that is completed using the goto statement:
#include <stdio.h>intMain () {intA =6, B = -, T; if(A <b) {T=A; A=b; b=T; }flag:if(A%b = =0) {printf ("%d\n", B); } Else{T=A; A=b; b= t%b; GotoFlag; } System ("Pause"); return 0;}
PS: If we use loops to do this, we need to use the middle part of the Flag~goto statement as the loop body.
2. The method of subtracting loss is more.
This algorithm is originally derived from the nine chapters of arithmetic, the content of the algorithm in modern Chinese translation after:
The first step: arbitrarily given two positive integers, judging whether they are even. If so, use a 2 reduction, or the second step if not. The second step: reduce the smaller number by a larger number, and then compare the resulting difference with the smaller number, and subtract the decimal number by the large numbers. Continue this operation until the resulting meiosis and difference are equal. The product of several 2 and second intermediate numbers in the first step is the desired greatest common divisor. The code is as follows:
#include <stdio.h>#include<math.h>intMain () {inti =0, T, x, a =6, B = -, result; while(A%2==0) && (b%2==0) ) {a/=2; b/=2; I+=1; } if(A <b) {T=A; A=b; b=T; } Do{x= A-b; if(b = =x) Break; A= (b > x)?b:x; b= (b < x)?b:x; } while(x); if(i = =0) {result=b; printf ("%d\n", result); } Else{result= (int) Pow (2, i) *b; printf ("%d\n", result); } System ("Pause"); return 0;}
The code of the Euclidean method is more efficient than the two methods, so it is more recommended to use the Euclidean method.
Finally, attach the result of the program running:
In C language implementation: Two number of greatest common divisor.