cant find the mistake here

1 visualización (últimos 30 días)
asaf omer
asaf omer el 1 de Jul. de 2019
Editada: Stephen23 el 1 de Jul. de 2019
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!

Respuestas (3)

Stephen23
Stephen23 el 1 de Jul. de 2019
Editada: Stephen23 el 1 de Jul. de 2019
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 comentarios
Stephen23
Stephen23 el 1 de Jul. de 2019
"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 el 1 de Jul. de 2019
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.

Iniciar sesión para comentar.


Star Strider
Star Strider el 1 de Jul. de 2019
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 comentario
asaf omer
asaf omer el 1 de Jul. de 2019
provides, same solution as before

Iniciar sesión para comentar.


Fangjun Jiang
Fangjun Jiang el 1 de Jul. de 2019
The mistake is that you need to insert this line as the first line inside your function.
v=[];

Categorías

Más información sobre Discrete Math en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by