Algorithm: Euclidean greatest common divisor (C language)

Euclidean a greatest common divisor algorithm

Known: A / B = C ······ R (A, B, C, R are integers)

Hypothesis: D is the remainder of A, D is the remainder of B, then D is a divisor of A and B

D is a divisor of A and B, then A and B are multiples of D, B * C is a multiple of D

Since A and D are each multiples of B * C, then A and B * C the difference in multiples of D is

A - B*C = R

Therefore, D is a multiple of R

If D is a divisor of A or B, then B is also a divisor D, and R

Late: (A, B) = (B, R)

From the above it can be proved that the greatest common divisor obtained

For example: greatest common divisor of 72 and 28

72 / 28 = 2 ······ 16

↓      ↓      ↓          ↓

28 / 16 = 1 ······ 12

↓      ↓      ↓          ↓

16 / 12 = 1 ······ 4

↓      ↓      ↓         ↓

12 / 4  =  3  ······ 0

We can now know the greatest common divisor of 72 and 28 is 4

 

. 1 #include <stdio.h> 
 2  int main () {
 . 3      int A;                     // the divisor 
. 4      int B;                     // dividend 
. 5      int R & lt = . 1 ;                 // remainder, is given the initial value. 1 
. 6      the printf ( " input divisor and dividend (separated by spaces): " );
 . 7      Scanf ( " % D% D " , & A, & B);
 . 8      the while (R & lt =! 0 ) {              // If a <b, also without reverse ab, supplier in the calculation 0 divisor than itself, in the next calculation can be reversed back from 
9         % a = R & lt b;
 10          a = b;
 . 11          b = R & lt;
 12 is      }
 13 is      the printf ( " the greatest common divisor of: D% \ n- " , a);         // this time has a value of b in the so It is a greatest common divisor of the output 
14      return  0 ;
 15 }

 

 

Guess you like

Origin www.cnblogs.com/zxkwdw/p/11986695.html