Greatest common divisor of two numbers is highest number smaller than or equal to minimum of two numbers which divides both numbers.
Algo would be like:
a,b<=10^5
for(int i=1;i<=min(a,b);i++)
{ if((a%i==0)&& (b%i==0))
gcd=i; }
More optimized algo given by euclid algorithm:
a,b<=10^9
Recursive definition:
int gcd(int a,int b)
{
if(b==0)
return a;
else
gcd(b,a%b);
}
Even more optimized algo for very long numbers
a,b<=10^200
Calling Function: gcd(a,mod(str,a));
int mod(char str[],int d)
{
int r=0,i;
for(i=0;str[i];i++)
{
r=10*r+(str[i]-'0');
r=r%d;
}
return r;
}
int gcd(int a,int b)
{
if(b==0)
return a;
else
gcd(b,a%b);
}
So Any gcd could be find out using above mentioned algos according to situations
Findng out lcm using gcd function
lcm(a,b)*gcd(a,b)=a*b;
Algo would be like:
a,b<=10^5
for(int i=1;i<=min(a,b);i++)
{ if((a%i==0)&& (b%i==0))
gcd=i; }
More optimized algo given by euclid algorithm:
a,b<=10^9
Recursive definition:
int gcd(int a,int b)
{
if(b==0)
return a;
else
gcd(b,a%b);
}
Even more optimized algo for very long numbers
a,b<=10^200
Calling Function: gcd(a,mod(str,a));
int mod(char str[],int d)
{
int r=0,i;
for(i=0;str[i];i++)
{
r=10*r+(str[i]-'0');
r=r%d;
}
return r;
}
int gcd(int a,int b)
{
if(b==0)
return a;
else
gcd(b,a%b);
}
So Any gcd could be find out using above mentioned algos according to situations
Findng out lcm using gcd function
lcm(a,b)*gcd(a,b)=a*b;
No comments:
Post a Comment