If tomorrow never comes

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

导航

辗转相除求最大公约数和最小公倍数

Posted on 2009-04-08 19:35  Brucegao  阅读(1038)  评论(0编辑  收藏  举报
1、求两个正整数的最大公约数与最小公倍数
【提示】:
(1)求两个非负正数m和n(要求m>n)的最大公约数可以使用辗转相除法。其算法描述为:
1)m除以n得到的余数为r(0<=r<n);
2)若r=0则算法结束,n为最大公约数。否则转3);

3)m=n,n=r,转1);

2、代码:(C#)

using System;
using System.Collections.Generic;
using System.Text;

namespace DivisorMutiple
{
    
class Program
    {
        
/// <summary>
        
/// Euclidean division
        
/// </summary>
        
/// <param name="m"></param>
        
/// <param name="n"></param>
            private static void gys(int m, int n)
            {
                
int p, q;
                p 
= m;
                q 
= n;
                
int gr, gb;
                
while (true)
                {
                    
if (p % q == 0)
                    {
                        gr 
= q;
                        
break;
                    }
                    
else
                    {
                        
int r = p % q;
                        p 
= q;
                        q 
= r;
                    }
                }
                gb 
= m * n / gr;
                Console.WriteLine(
"最大公约数是:{0},最小公倍数{1}", gr, gb);
            }
        
            
static void Main()
            {
                
int m, n;
                Console.WriteLine(
"正输入整数m");
                m 
= Convert.ToInt32(Console.ReadLine());
                Console.WriteLine(
"输入正整数n");
                n 
= Convert.ToInt32(Console.ReadLine());
                
if (m <= n)
                {
                    Console.WriteLine(
"要求m>n");
                    Main();
                }
                
else
                {
                    gys(m, n);
                }
                Console.ReadLine();
            }
    }
}