Solve system of equations with two unknowns (should be the smallest rational number possible)

1 visualización (últimos 30 días)
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.

Respuestas (1)

Torsten
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))
Local minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance.
sol = 1×2
2.2361 2.2361
function [c,ceq] = nonlcon(x,k)
ceq = x(1)*x(2) - k;
c = [];
end
  2 comentarios
Valeria
Valeria el 4 de Oct. de 2022
I made mistake when phrasing the question, can you please take a look at it again. Thank you
Torsten
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).'
v = 7×1
2 2 2 2 3 3 31933578773
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
minimum = uint64 31933578917
factor1
factor1 = 144
factor2
factor2 = uint64 31933578773

Iniciar sesión para comentar.

Productos


Versión

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by