每周算法之————最大公约数

穷举法:

#include<iostream>

using namespace std;

unsigned long GCD(unsigned long a, unsigned long b)

{

       if(a == 0)

              return b;

       else if(b == 0)

              return a;

    else if(a == b)

              return a;

       unsigned long gcd;

       gcd = a>b?b:a;

       while(gcd > 1)

       {

              if((a%gcd==0) && (b%gcd==0))

                     return gcd;

              gcd--;

       }

       return gcd;

}

void main()

{

       unsigned long a,b;

       cout<<"请输入a 和b:>";

       cin>>a>>b;

       unsigned long gcd = GCD(a,b);

       cout<<"gcd = "<<gcd<<endl;

}

 

相减法:

unsigned long gcd;
while
(a!=b) { gcd = a>b?(a-=b):(b-=a); } return gcd;

相除法:

unsigned long mod = a%b;
while(mod != 0)
{
  a = b;
  b = mod;
 mod = a%b;         
}

递归:

unsigned long GCD(unsigned long a, unsigned long b)
{
    if(b == 0)
        return a;
    else
        return GCD(b, a%b);
}

 

posted @ 2017-03-15 09:20  zhangtianyu  阅读(203)  评论(0编辑  收藏  举报