06 December 2015

Binary GCD code

There are many algorithm to find GCD of any two number. Here is an algorithm . For details visit  https://en.wikipedia.org/wiki/Binary_GCD_algorithm

/***
Md. Namzul Hasan
Shahjalal University of Science & Technology,Sylhet.
hasan08sust@gmail.com
***/
#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
typedef int in ;
typedef unsigned long long ull ;
const double pi = 2*acos(0) ;
#define maxi 40000
#define pf printf
#define sc scanf
#define pb push_back
#define MEM(x,y) (memset((x),(y),sizeof(x)))
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define load(array,size)  for(int i=0 ; i<size ; i++) cin>>array[i]  ;
#define new_line  pf("\n")
#define clear_data(array) memset(array,0,sizeof(array))
#define highest_int 2147483647

int g ,d ;

int binaryGcd(int num1, int num2)
{

    int cnt =0 , tmp ;
    while(!(num1&1) && !(num2&1))
    {
        num1>>=1 ;
        num2>>=1 ;
        cnt++ ;
    }

    do
    {

        while(!(num1&1))
        {
            num1>>=1 ;
        }
        while(!(num2&1))
        {
            num2>>=1 ;
        }

        if(num1>num2)
        {
            num1 = (num1-num2)>>1 ;
        }
        else
        {
            tmp = num1 ;
            num1 = (num2 -num1)>>1 ;
            num2 =tmp ;
        }
    }
    while(!(num1==num2 || num1==0)) ;

    return num2<<cnt ;

}


int main()
{
    int num1, num2 ;
    while(true)
    {

        sc("%d %d",&num1,&num2) ;
        int gcd = binaryGcd(num1,num2) ;
        pf("GCD of %d %d is: %d\n",num1,num2,gcd) ;
    }


    return 0;
}

No comments:

Post a Comment

UVA 10679 - I Love Strings!!