实现扩展欧几里德算法

时间:2016-04-12 19:47:43

标签: function haskell greatest-common-divisor

我想创建一个函数组合,它给出两个整数n和m,返回一个三元组的整数 (a,b,gcd(n,m))这样: am + bn = gcd(n,m) 不应该假设整数总是积极的。

 gcd :: Int -> Int -> Int
 gcd n m 
 | n == m  = n
 | n > m = gcd (n-m) m
 | n < m  = gcd n (m-n)

 combine :: Int ->Int -> (Int,Int,Int)
 x1=1; y1=0; x2=0; y2=1
 while ( m /=0 ) 
 (    q=div n m ; r=mod n m ; n=m ; m=r
     t=x2 ; x2=x1-q*x2 ; x1=t
     t=y2 ; y2=y1-q*y2 ; y1=t    )
 combine n m = (x1,y1,gcd(n,m))

您将找到一个截屏图片链接。点击我---&gt; ![link] http://prikachi.com/images.php?images/238/8749238o.png如果有人有解决方案,并且知道我可以替换什么来创建这个功能,我将不胜感激。 测试功能:组合3 2应该给出这个结果=&gt; (1,-1,1)

1 个答案:

答案 0 :(得分:0)

我想你可能正在寻找这样的东西:

combine :: Int ->Int -> (Int,Int,Int)
combine n m = (x1, y1, gcd n m) where
  (x1, y1) = gcdext n m

gcdext :: Int -> Int -> (Int, Int)
gcdext n m = gcdexthelper n m 1 0 0 1 where
  gcdexthelper n m x1 y1 x2 y2 
   | m == 0 = (x1, y1)
   | otherwise = gcdexthelper m r x1p y1p x2p y2p where
     q = div n m
     r = mod n m
     x1p = x2
     y1p = y2
     x2p = x1 - q * x2
     y2p = y1 - q * y2

你当然可以用while循环来实现它,但我相信递归在Haskell中更具可读性,所以我在这里使用它。

顺便说一下,GCD是Haskell中的标准库函数,所以不需要编写自己的函数。