Chinaunix首页 | 论坛 | 博客
  • 博客访问: 491808
  • 博文数量: 164
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 2240
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-07 12:55
文章存档

2008年(164)

我的朋友

分类: C/C++

2008-03-09 19:32:49

C语言版:
/*欧几里德算法:辗转求余
  原理: gcd(a,b)=gcd(b,a mod b)
  当b为0时,两数的最大公约数即为a

  getchar()会接受前一个scanf的回车符
*/

#include

void main()
{
    int temp;
    int a,b;
    scanf("%d",&a);
    scanf("%d",&b);
    printf("the greatest common factor of %d and %d is ",a,b);
    while(b!=0)
    {
        temp=b;
        b=a%b;
        a=temp;
    }
    printf("%d\n",a);
    getchar();
    getchar();
}


C++/java语言版:
    void swap(int & a, int & b)
    {
        int c = a;
        a = b;
        b = c;
    }
    int gcd(int a,int b)
    {
        if(0 == a )
        {
            return b;
        }
        if( 0 == b)
        {
            return a;
        }
        if(a > b)
        {
            swap(a,b);
        }
        int c;
        for(c = a % b ; c > 0 ; c = a % b)
        {
            a = b;
            b = c;
        }
        return b;
    }
阅读(655) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~