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 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Arslan Ahmad
am 11 Okt. 2017
Kommentiert: Divya
am 12 Mär. 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 Kommentare
MUTHUKUMAR SETHURAM
am 11 Okt. 2017
Bearbeitet: Walter Roberson
am 11 Okt. 2017
NumbersRange = 47 : 97;
Prime_Index = isprime(NumbersRange);
NumbersRange(Prime_Index)
Akzeptierte Antwort
Walter Roberson
am 11 Okt. 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 Kommentare
Walter Roberson
am 11 Okt. 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
Weitere Antworten (1)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!