[Scilab-users] Variable user equation input (2, 3 or more)
Lester Anderson
arctica1963 at gmail.com
Sat Apr 30 13:09:35 CEST 2022
Cleaned up the code using Loops
clear
// Chinese Remainder Theorem (CRT) for 3 congruence equations// e.g. x
≡ 3 mod 5; x ≡ 1 mod 7; x ≡ 6 mod 8// result ≡ 78 mod 280
m=evstr(x_dialog(['Moduli values:
'],'1'));a=evstr(x_dialog(['Remainder values: '],'1'));m1=m(1);
m2=m(2); m3=m(3);a1=a(1); a2=a(2); a3=a(3);n=evstr(x_dialog(['Number
of iterations: '],'1'));
M=prod(m);
for i=1:length(m)
M_ratio(i) = M/m(i)end
for i=1:length(m)
for j=1:n
if modulo(((M_ratio(i)*j)-1),m(i)) == 0
M_inv(i)=j;
xn(i)=(a(i)*M_ratio(i)*M_inv(i));
end
endend
x = modulo(sum(xn),M)
// Console output://mprintf('\nThe solution for (x): %d mod %d',x, M)
messagebox(['x ≡ '+string(a1)'+' mod '+string(m1)' ...
'x ≡ '+string(a2)'+' mod '+string(m2)' ...
'x ≡ '+string(a3)'+' mod '+string(m3)' ...
'The solution for (x): '+string(x)+' mod '+string(M)'], ...
'Solution of 3 congruence equations')
On Sat, 30 Apr 2022 at 06:14, Lester Anderson <arctica1963 at gmail.com> wrote:
> Hello all,
>
> I have a simple code which computes applies the Chinese Remainder theorem
> (for a single variable) given three input congruence equations to solve for
> x; not very elegant but it works:
>
> My query, is it possible to make this more generalised and vary the number
> of input equations and give the user an option to specify the number of
> equations?
> For example, one may have 2, 4 or more equations.
>
> Any pointers would be helpful.
>
> Thanks
> Lester
>
> clear
> // Chinese Remainder Theorem (CRT) for 3 congruence equations// e.g. x ≡ 3 mod 5; x ≡ 1 mod 7; x ≡ 6 mod 8// result ≡ 78 mod 280
> m=evstr(x_dialog(['Moduli values: '],'1'));r=evstr(x_dialog(['Remainder values: '],'1'));m1=m(1); m2=m(2); m3=m(3);r1=r(1); r2=r(2); r3=r(3);n=evstr(x_dialog(['Number of iterations: '],'1'));
> M=m1*m2*m3;M1=M/m1; M2=M/m2; M3=M/m3;
> for i=1:n
> if modulo(((M1*i)-1),m1) == 0 then
> M1_inv=i;
> end
>
> if modulo(((M2*i)-1),m2) == 0 then
> M2_inv=i;
> end
>
> if modulo(((M3*i)-1),m3) == 0 then
> M3_inv=i;
> endend
> x1=(r1*M1*M1_inv);x2=(r2*M2*M2_inv);x3=(r3*M3*M3_inv);
> x = modulo((x1 + x2 + x3), M);
> messagebox(['x ≡ '+string(r1)'+' mod '+string(m1)' ...
> 'x ≡ '+string(r2)'+' mod '+string(m2)' ...
> 'x ≡ '+string(r3)'+' mod '+string(m3)' ...
> 'The solution for (x): '+string(x)+' mod '+string(M)'], ...
> 'Solution of 3 congruence equations')
>
>
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.scilab.org/pipermail/users/attachments/20220430/5cb14311/attachment.htm>
More information about the users
mailing list