필터 지우기
필터 지우기

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

채택된 답변

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

Robert
Robert 2019년 4월 10일
Just do
r=gcd(a,b)==1
instead

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by