I am writing a code that will check two numbers whether they are relatively prime or not if they are it would return 1 else 00the problem is that i am getting 1 all the times. Kindly help me midfy my code.
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Arslan Ahmad
el 11 de Oct. de 2017
Comentada: Divya
el 12 de Mzo. de 2023
function [r]=prime(a,b)
a=input('Enter 1st number=');
b=input('Enter 2nd number=');
% factors for 1st number
K=1:a;
D1 = K(rem(a,K)==0)
% factors for 2nd number
K=1:b;
D2 = K(rem(b,K)==0)
n1=length(D1);
n2=length(D2);
for i=2:n1
for o=2:n2
if (D1(i)==D2(o))
r=0;
break
else
if (D1(i)~=D2(o))
r=1;
end
end
end
end
2 comentarios
MUTHUKUMAR SETHURAM
el 11 de Oct. de 2017
Editada: Walter Roberson
el 11 de Oct. de 2017
NumbersRange = 47 : 97;
Prime_Index = isprime(NumbersRange);
NumbersRange(Prime_Index)
Respuesta aceptada
Walter Roberson
el 11 de Oct. de 2017
You have a break within a double-nested for loop. That break is only going to break from the inner for loop: you keep running the outer for loop. As long as at least one place a 1 is assigned, then the only thing that has any effect on the output is the last iteration of the outer for loop, because you keep running the outer loop after the inner break.
Your code has another bug, by the way: 1 will divide all values, and when you compare the ones from both sides you say "No, not relatively prime"
Your code is quite inefficient. You should consider using intersect() or ismember()
3 comentarios
Walter Roberson
el 11 de Oct. de 2017
Minimal modification (rather than "good code")
r = 1;
for i=2:n1
for o=2:n2
if (D1(i)==D2(o))
r=0;
break
else
if (D1(i)~=D2(o))
r=1;
end
end
if r == 0
break
end
end
Más respuestas (1)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!