i have found following pseudo-code for extended euclidean algorithm
i implemented following algorithm
function [x1,y1,d1]=extend_eucledian(a,b)
if b==0
x1=1;
y1=0;
d1=a;
return;
end
[x1,y1,d1]=extend_eucledian(b,mod(a,b));
x1=y1;
y1=x1-floor(a/b)*y1;
d1=d1;
end
when i run following this program, i got following result
[x1,y1,d1]=extend_eucledian(23,20)
x1 =
0
y1 =
0
d1 =
1
i guess that [x1,y1,d1] are not changing their values during the iteration, for instance , i have tried following code
function [x1,y1,d1]=extend_eucledian(a,b)
if b==0
x1=1;
y1=0;
d1=a;
return;
else
x1=y1;
y1=x1-floor(a/b)*y1;
d1=d1;
end
[x1,y1,d1]=extend_eucledian(b,mod(a,b));
end
but i got
>> [x1,y1,d1]=extend_eucledian(23,20)
Undefined function or variable 'y1'.
Error in extend_eucledian (line 8)
x1=y1;
how can i fix this problem? where i am making mistake?
The problem can be solved by introducing intermediate working variables, that will store the result of the recursive call:
function [x,y,d]=extended_euclid(a,b)
if b==0
x=1;
y=0;
d=a;
return;
end
[x1,y1,d1]=extended_euclid(b,mod(a,b));
x=y1;
y=x1-floor(a/b)*y1;
d=d1;
end
This function works as expected:
>> [x, y, d] = extended_euclid(23,20)
x =
7
y =
-8
d =
1
>> [x, y, d] = extended_euclid(25,20)
x =
1
y =
-1
d =
5