Advertisement
mgaikema

Extended Euclidean Algorithm

Jul 17th, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 0.76 KB | None | 0 0
  1. rm(list=ls())
  2. # Remove pre-existing objects
  3.  
  4. #' Extended Euclidean Algorithm
  5. #' Computes d=gcd(u,v) and a,b that satisfy
  6. #' a*u+b*v=d
  7. #'
  8. #' @param u,v: Two integers, with u>v
  9. #' @return A list with a,b,d, such that au+bv=d
  10. gcd_E = function(u,v){
  11.     m = matrix(c(1,0,0,1),nrow=2)                       # m = |1 0|
  12.     n = 0                                               #     |0 1|
  13.    
  14.     while(v != 0){
  15.         q = floor(u/v) # Get u/v, less the remainder
  16.         m =  m %*% matrix(c(q,1,1,0),nrow=2,byrow=T)    # m = m * |q 1|
  17.         temp = v                                        #         |1 0|
  18.         v = u - q*v # (u,v)=(v,u-q*v)
  19.         u = temp
  20.         n = n+1
  21.     }
  22.    
  23.     return( list(d=u, a=(-1)^n*m[2,2], b=(-1)^(n+1)*m[1,2]) )
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement