首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

求两个数的最贵族约数

2013-01-17 
求两个数的最大公约数求两个正整数的最大公约数,怎么编写程序[解决办法]#includestdio.hmain(){int a,b,

求两个数的最大公约数
求两个正整数的最大公约数,怎么编写程序
[解决办法]

#include<stdio.h>
main()
{int a,b,r,i;
scanf("%d",&a,&b);
r=x>=y?x:y;
for(i=1;i<=r;i++)
if(x%i==0&&y%i==0)
n=i;
printf("%d",n);
}

[解决办法]

#include <stdio.h>

int main(int argc, char* argv[])
{
int m, n;
int m_cup, n_cup, res; /*被除数, 除数, 余数*/
printf("Enter two integer:\n");
scanf("%d %d", &m, &n);
if (m > 0 && n >0)
{
m_cup = m;
n_cup = n;
res = m_cup % n_cup;
while (res != 0)
{
m_cup = n_cup;
n_cup = res;
res = m_cup % n_cup;
}
printf("Greatest common divisor: %d\n", n_cup);
printf("Lease common multiple : %d\n", m * n / n_cup);
}
else printf("Error!/n");
return 0;


[解决办法]
可以使用辗转相除法,也就是递归的思想
#include <stdio.h>
int main(void)
{
int a,b,c,t;
printf("input numbers:");
scanf("%d%d",&a,&b);
c=a%b;
while(1)
{
if(c==0)
{
printf("最大公约数是:%d\n",b);
break;
}
else
{
t=b;
b=c;
c=t%c;
if(c==0)
{
printf("最大公约数是:%d\n",b);
break;
}
}
}
return 0;
}

[解决办法]
效率最高的代码:

//BigInt为自己实现的一个大整数类,IsEven()判断是否为偶数 
BigInt gcd(BigInt x,BigInt y)
{
if(x < y)
  return gcd(y,x);
    if(y == 0)
       return x;
    else{
       if(IsEven(x))
   {
     if(IsEven(y)) //情形1,x,y均为偶数 
       return 2 * gcd(x >> 1, y >> 1);
          else  //情形2,x为偶,y为奇 
            return gcd(x >> 1, y);
   }
   else
   {
     if(IsEven(y)) //情形3,x为奇,y为偶 
       return gcd(x, y >> 1);
        else  //情形4,x,y均为奇 
          return gcd(y, x - y);
   }
    }
}

热点排行
Bad Request.