Implementing Extended Euclidean algorithm

房东的猫 提交于 2019-12-13 09:57:27

问题


I want to make a function combine which given two integers n and m, returns a triple of integers (a, b, gcd(n, m)) such that: am + bn = gcd(n, m) Should not assume that the integers will always be positive.

 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))

You will find a screen capture picture link. Click me---> ![link] http://prikachi.com/images.php?images/238/8749238o.png Please if someone have a solution and have idea what I could replace to create the function, would be much appreciated. Test for the function: combine 3 2 should give this result => (1,-1,1)


回答1:


I think you might be looking for something like this:

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

You can of course implement the same with a while loop, but I believe recursion is much more readable in Haskell, so I used it here.

And by the way, GCD is a standard library function in Haskell, so no need to write your own.



来源:https://stackoverflow.com/questions/36582754/implementing-extended-euclidean-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!