Three ways to find the greatest common divisor

one. Greatest common divisor: is the largest integer that can divide two integers, the following three methods:

/*1. Exhaustive method
 
 
Since the greatest common divisor of a and b cannot be greater than the smaller of the two, that is, check all integers from 1 to t, and t that satisfies the common divisor condition is the greatest common divisor. */
#include <stdio.h>#include <stdlib.h>int Gcd(int a,int b){ int t; if( a<=0 ||b<=0 ) return -1; t=a<b? a:b; for(int i=t;i>0;i--){ //Starting from the smaller t of a and b, try every possible one by 1 if(a%i==0&&b%i ==0) return i; } return 1;}int main(){ int a,b,c; scanf("%d%d",&a,&b); c = Gcd(a,b); if(c !=-1) printf("The greatest common divisor of %d and %d is %d\n",a,b,c); else printf("%d and %d have no greatest common divisor!",a,b ); return 0;}
/*2. Euclidean algorithm or tossing and dividing method
    Perform continuous remainder operations on positive integers a and b until the remainder is 0. At this time, the non-zero divisor is the greatest common divisor.
    即Gcd(a,b)=Gcd(b,r)
    For example, the greatest common divisor of 50 and 15 Gcd(50,15)=Gcd(15,5)=Gcd(5,0)
*/
#include <stdio.h>
#include <stdlib.h>

int Gcd(int a,int b){
    int r;
    if( a<=0 ||b<=0 ) return -1;
    do{
        r = a % b;
        a = b;
        b = r;
    }while(r!=0);
    return a;
}
intmain()
{
    int a,b,c;
    scanf("%d%d",&a,&b);
    c = Gcd(a,b);
    if(c!=-1) printf("The greatest common divisor of %d and %d is %d\n",a,b,c);
    else printf("%d and %d have no greatest common divisor!",a,b);
    return 0;
}

/*3. Recursion
    When a>b, if a contains the same greatest common divisor as b, then ab also has the same greatest common divisor as b.
    Until a=b, then a or b is the greatest common divisor.
*/
#include <stdio.h>
#include <stdlib.h>

int Gcd(int a,int b){
    if( a<=0 ||b<=0 ) return -1;
    if(a==b) return a;
    else if(a>b) return Gcd(a-b,b);
    else return Gcd(b,b-a);
}
intmain()
{
    int a,b,c;
    scanf("%d%d",&a,&b);
    c = Gcd(a,b);
    if(c!=-1) printf("The greatest common divisor of %d and %d is %d\n",a,b,c);
    else printf("%d and %d have no greatest common divisor!",a,b);
    return 0;
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324662629&siteId=291194637