What is the fastest way to find the GCD of two numbers?

左心房为你撑大大i 提交于 2019-11-29 18:27:21
int gcd(int a, int b)
{

    if(b == 0) {
            return a;
    }
    else {
        return gcd(b, a % b);
    }
}

The following code uses the normal method that we humans use to calculate the GCD and is by far, according to me the fastest way to find GCD(HCF) of 2 numbers:

#include <iostream>

using namespace std;

int main()
{
    int N1;
    int N2;
    cin<<N1;
    cin<<N2;
    int small=N1;
    int big=N2;

    if (N1>N2){
        N1=small;
        N2=big;
    }

    int P=1;
    int i=1;

    while (i<=N1){
        if (N1%i==0 && N2%i==0){
            N1=N1/i;
            N2=N2/i;
            P=P*i;
            i=1;
        }
        i=i+1;
    }
    cout<<"GCD= "<<P;
    return 0;
}
#include<stdio.h>
int main()
{
   int a,b,a1,b1;
   printf("Enter two numbers:");
   scanf("%d%d",&a,&b);
   a1=a;b1=b;
   while(a!=b)
   {
      if(a>b)
        a=a-b;
      else
        b=b-a;
   }
   printf("GCD of %d and %d is %d\n",a1,b1,a);
   printf("LCM of %d and %d is %d",a1,b1,(a1*b1/a));
}

For small numbers use binary GCD (which is faster Euclid's GCD algorithm) & for large numbers try Lehmer's algorithm.

Binary GCD: https://www.google.com/amp/s/www.geeksforgeeks.org/steins-algorithm-for-finding-gcd/amp/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!