最大公约数的几种求解方式


题目描述:求解两个整数(不能是负数)的最大公约数(要求两数不能同时为0)


方法一:穷举法

   

#include
using namespacestd;
unsigned longGCD(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 ="<

方法二 : 相减法

#include
using namespacestd;
unsigned longGCD(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;
       while(a != b)
       {
              gcd = a > b ? (a-=b) : (b-=a);
       }
       return gcd;
}
void main()
{
       unsigned long a,b;
       cout<<"请输入a 和b:>";
       cin>>a>>b;
       unsigned long gcd = GCD(a,b);
       cout<<"gcd ="<

方法三 : 欧几里德辗转相除法

#include
using namespacestd;
unsigned longGCD(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 mod = a % b;
       while(mod != 0)
       {
              a = b;
              b = mod;
              mod = a % b;
       }
       return b;
}
void main()
{
       unsigned long a,b;
       cout<<"请输入a 和b:>";
       cin>>a>>b;
       unsigned long gcd = GCD(a,b);
       cout<<"gcd ="<

方法四 : 欧几里德辗转相除法   递归实现

#include
using namespacestd;
unsigned longGCD(unsigned long a, unsigned long b)
{
       if(b == 0)
              return a;
       else
              return GCD(b, a%b);
}
void main()
{
       unsigned long a,b;
       cout<<"请输入a 和b:>";
       cin>>a>>b;
       unsigned long gcd = GCD(a,b);
       cout<<"gcd ="<


你可能感兴趣的:(C语言笔试题)