using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 欧几里得算法(求两个正整数的最大公约数)
/// 右称:辗转相除法
///
/// 假如需要求 1997 和 615 两个正整数的最大公约数,用欧几里德算法,是这样进行的:
/// 1997 = 3 * 615 + 152
/// 615 = 4 * 152 + 7
/// 152 = 21 * 7 + 5
/// 7 = 1 * 5 + 2
/// 5 = 2 * 2 + 1
/// 2 = 2 * 1 + 0
///当被加的数为 0 时,就得出了 1997 和 615 的最大公约数 1。
///
/// </summary>
public class EuclideanAlgorithmScript : MonoBehaviour {
public int Int_a;
public int Int_b;
private int _Int_Residue; //余数(MOD)
private int _Int_Result; //商值
/// <summary>
/// 欧几里得算法
/// </summary>
public void OnClick_GetsTheGCD_Method()
{
//Debug.Log(GetGCD(Int_a, Int_b));
Debug.Log("最大公约数是 : " + GetGCD(Int_a, Int_b));
}
/// <summary>
/// 欧几里得算法
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
private int GetGCD(int a,int b)
{
if (a > b)
{
_Int_Result = a / b; //获取商值
_Int_Residue = a % b; //获取余值
if (_Int_Residue == 0) //当余数为0时,则找到最大公约数
{
return b; //公约数为被除数
}
else
{ //否则重新计算
a = b;
b = _Int_Residue;
return GetGCD(a, b);
}
}
else
{
_Int_Result = b / a; //获取商值
_Int_Residue = b % a; //获取余值
if (_Int_Residue == 0) //当余数为0时,则找到最大公约数
{
return a; //公约数为被除数
}
else
{ //否则重新计算
b = a;
a = _Int_Residue;
return GetGCD(a, b);
}
}
}
}