cant find the mistake here
조회 수: 1 (최근 30일)
이전 댓글 표시
hola,
i try to write a function that finds "twins prime" among 2 given values.
twins prime are prime numbers that the difference between them is 2
for example (3,5) , (5,7) and etc.
but somehow function provides me an empty vector.
can some1 please help with that tissue?
function [v]=twins(a,b)
for i =1:a
for j =1:b
if isprime (i) && isprime(j) && i+2==j
v=[v,j,i];
end
end
end
end
thanks!
댓글 수: 0
답변 (3개)
Stephen23
2019년 7월 1일
편집: Stephen23
2019년 7월 1일
Well you made a good starting attempt, the main bug with your code are these ranges:
for i = 1:a
for j = 1:b
Using those ranges, do you ever generate pairs of values between a+1 and b ? (hint: no, and you can check this quite easily yourself by simply printing those values in the loops). You need to think about what values you actually need to loop over (hint: a:b)
However your two loop-concept is far too complex, and also very inefficient (think about what the two loops are doing, and how often their loop iterator variable values will differ by two (hint: extremely rarely)). A simplified, much more efficient version of your concept using one loop:
function m = twins(a,b)
m = nan(2,0);
for n = a:b-2
v = [n;n+2];
if all(isprime(v))
m = [m,v];
end
end
end
and tested:
>> twins(3,19)
ans =
3 5 11 17
5 7 13 19
Or no loops:
function m = twins(a,b)
m = [a:b-2;a+2:b];
m = m(:,all(isprime(m),1));
end
and tested:
>> twins(3,19)
ans =
3 5 11 17
5 7 13 19
댓글 수: 3
Stephen23
2019년 7월 1일
"can u please explain me about nan and all orders?"
nan is used to define an empty 2x0 numeric array. I do not know what "orders" you refer to.
"in addition, what went wrong in my code?"
I explain this at the start of my answer.
Steven Lord
2019년 7월 1일
As its documention page states, the all function is used to "Determine if all array elements are nonzero or true".
As Stephen uses it, the if is satisfied if all the elements of isprime(v) are true, or to reword it slightly if all the elements of v are prime.
Star Strider
2019년 7월 1일
Try this:
function v = twins(a,b)
v = [];
for i =1:a
for j =1:b
if isprime (i) && isprime(j) && abs(i-j)==2
v=[v;j,i];
end
end
end
end
The test should be ‘abs(i-j)==2’.
Fangjun Jiang
2019년 7월 1일
The mistake is that you need to insert this line as the first line inside your function.
v=[];
참고 항목
카테고리
Help Center 및 File Exchange에서 Discrete Math에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!