If tomorrow never comes

The meaning of life is creation,which is independent an boundless.

导航

欧几里得算法(C++)

Posted on 2010-05-12 17:22  Brucegao  阅读(1120)  评论(0编辑  收藏  举报

算法:给定两个正整数m和n,求它们的最大公因子,即能够同时整除m和n的最大正整数。

  1. [求余数]以n除m并令r为所得余数(我们将有0<=r<n).

  2. [余数为0?]若r=0,算法结束;n既为答案.

  3.[互换]置m<-n,n<-r,并返回步骤1

 

代码(不成熟之处还望指教):

 

代码
// consoleApp.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include 
<iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    
int m,n;
    
int con;
    cin
>>m>>n;
    
int Euclid(int,int);
    con
=Euclid(m,n);
    cout
<<con<<endl;
}

int Euclid(int m,int n)
{
    
//int m1=m,n1=n;
    if(m<=0||n<=0)
        
return 0;

    
if(m<n)
    {
        
int temp=m;
        m
=n;
        n
=temp;
    }

    
int r=m%n;
    
while(r!=0)
    {
        
        m
=n;
        n
=r;
        r
=m%n;
    }

    
return n;
}

 

最大公因子求出来了,那么最小公倍数呢?
其实只要在运算函数里面返回两个数的积与最大公因子的比值即可,既:m1*n1/n