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 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
MUTHUKUMAR SETHURAM
2017 年 10 月 11 日
編集済み: Walter Roberson
2017 年 10 月 11 日
NumbersRange = 47 : 97;
Prime_Index = isprime(NumbersRange);
NumbersRange(Prime_Index)
採用された回答
Walter Roberson
2017 年 10 月 11 日
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 件のコメント
Walter Roberson
2017 年 10 月 11 日
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
その他の回答 (1 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!