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
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;
}
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/
int gcd(int a, int b)
{
if(b == 0) {
return a;
}
else {
return gcd(b, a % b);
}
}
#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));
}