cant find the mistake here

조회 수: 1 (최근 30일)
asaf omer
asaf omer 2019년 7월 1일
편집: Stephen23 2019년 7월 1일
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!

답변 (3개)

Stephen23
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
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
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
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’.
  댓글 수: 1
asaf omer
asaf omer 2019년 7월 1일
provides, same solution as before

댓글을 달려면 로그인하십시오.


Fangjun Jiang
Fangjun Jiang 2019년 7월 1일
The mistake is that you need to insert this line as the first line inside your function.
v=[];
  댓글 수: 1
asaf omer
asaf omer 2019년 7월 1일
still doesnt work

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Discrete Math에 대해 자세히 알아보기

태그

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by