Solve system of equations with two unknowns (should be the smallest rational number possible)
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
I have to variables a and b
a*b = 25 = k
a and b should be the smallest integers possible, (therefore the result I should get from matlab is a = 5 and b =5, a=b will not always be the case, will depend of the value of k)
When I solve it this way I get the following:
k = 25
syms a b
eqn1 = a*b == k;
N_Results2 = solve(eqn1,[a b],'Real',true);
N_Results2 =
struct with fields:
a: 25
b: 1
How do I constraint it so that both numbers are integers and they also are the smallest numbers possible.
0 comentarios
Respuestas (1)
Torsten
el 4 de Oct. de 2022
Editada: Torsten
el 4 de Oct. de 2022
Easy for a,b real:
a = b = sqrt(k).
More involved for a,b rational.
For a,b real it can be solved as an optimization if you don't believe that a=b=sqrt(k) solves the problem:
min: a + b
s.c. a*b = k
k = 5;
x0 = [1 k];
fun = @(x)x(1)+x(2);
sol = fmincon(fun,x0,[],[],[],[],[],[],@(x)nonlcon(x,k))
function [c,ceq] = nonlcon(x,k)
ceq = x(1)*x(2) - k;
c = [];
end
2 comentarios
Torsten
el 4 de Oct. de 2022
Editada: Torsten
el 5 de Oct. de 2022
I assume you want to find integers a and b with a*b = k and a+b as small as possible.
You can change this to max(a,b) as small as possible or whatever you like in the code.
k = uint64(4598435343312);
v = factor(k).'
n = numel(v);
if n == 1
disp('n is prime')
return
end
s = 2^n;
result = logical(dec2bin(0:s-1)-'0');
f1 = 1;
f2 = k;
minimum = k+1;
for i = 2:size(result,1)-1
factor1 = prod(v(result(i,:)));
factor2 = k/factor1;
if factor1 + factor2 < minimum
minimum = factor1 + factor2;
f1 = factor1;
f2 = factor2;
end
end
minimum
factor1
factor2
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!