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

后端 未结 4 801
鱼传尺愫
鱼传尺愫 2020-12-22 12:48

I have an array of size n. I need to find the GCD of each element with a given number and if it\'s greater than 1, add it to another array. What\'s the fastest way to do thi

相关标签:
4条回答
  • 2020-12-22 13:18

    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;
    }
    
    0 讨论(0)
  • 2020-12-22 13:23

    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/

    0 讨论(0)
  • 2020-12-22 13:24
    int gcd(int a, int b)
    {
    
        if(b == 0) {
                return a;
        }
        else {
            return gcd(b, a % b);
        }
    }
    
    0 讨论(0)
  • 2020-12-22 13:24
    #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));
    }
    
    0 讨论(0)
提交回复
热议问题