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=[];
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!