Filter löschen
Filter löschen

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)
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

Akzeptierte Antwort

Walter Roberson
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
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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Robert
Robert am 10 Apr. 2019
Just do
r=gcd(a,b)==1
instead

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!

Translated by