Algorithm in C(1): Euclid's algorithm

Euclid's algorithm 是求 Greatest Common Divisor 的。 Euclid's algorithm 利用最大公约数的性质,对两个数之进行减法和交换运算,最后判断0之外没有任何其他操作了,非常适合计算机运算。 那好看看C语言的实现:

ContractedBlock.gif ExpandedBlockStart.gif Code
/*                                        */
/*  Implementation of Euclid's algorithm1 */
/*      Programmed by Lee jaekyu          */
/*                                        */
#include 
<stdio.h>

int get_gcd(int u, int v)
{
    
int t;
    
while(u)
    {
        
if (u<v)
        {
            t
=u; u=v; v=t;
        }
        u
=u-v;
    }
    
return v;
}

void main (void)
{
    
int u,v;
    puts (
"\n EUCLID : Get GCD of two positive integer"
          
"\n     Input 0 to end program ");

    
while(1)
    {
        puts (
"\n Iput two positive integer  ");
        scanf(
"%d %d"&u,&v);
        
        
if (u<0 ||v<0)
            
continue;
        
if (u==0 || v==0)
            
break;
        printf(
"\n GCD of %d and %d is %d.", u, v, get_gcd(u,v));
    }
}

 

 运行结果:

ContractedBlock.gif ExpandedBlockStart.gif Code
rize@rize-laptop ~/Algorithm-C> gcc -o euclid_GCD euclid_GCD.c 
euclid_GCD.c: 
In function ‘main’:
euclid_GCD.c:
22: warning: return type of ‘main’ is not ‘int’
rize
@rize-laptop ~/Algorithm-C> ls
euclid_GCD
*  euclid_GCD.c
rize
@rize-laptop ~/Algorithm-C> ./euclid_GCD 

 EUCLID : Get GCD of two positive integer
     Input 
0 to end program 

 Iput two positive integer  
45 90

 GCD of 
45 and 90 is 45.
 Iput two positive integer  
3 98

 GCD of 
3 and 98 is 1.
 Iput two positive integer  
34 89

 GCD of 
34 and 89 is 1.
 Iput two positive integer  
0 0
rize
@rize-laptop ~/Algorithm-C>

转载于:https://www.cnblogs.com/jinrize/archive/2009/10/27/1590706.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值