What is wrong with my code?

Hi, im trying to create a function which returns every prime number between 1 and 'N' Number using other two fuction which works fine.
This are the two function:
function [q] = Elimina_Multiplos(s,N) %This function eliminates multiples of N, except N and 1
q = s;
q(~mod(q,N) & q ~= N & N ~= 1) = [];
end
and
function [ A ] = Numeros_Iguales( a,b ) %This function looks fot similar numbers between two arrays, and returns only such numbers
A = [];
for n = 1:length (a)
for m = 1:length(b)
if a(n) == b(m)
A = [A,n];
end;
end;
end;
end
AND THIS IS THE FUNCTION which returns only the primes numbers between 1 and N number.
function [p] = Primos(N)
q = [];
r = [];
p = 1:10;
for x = 1:N
q = Elimina_Multiplos(1:N,x);
r = Numeros_Iguales(p,q);
p = r;
end;
end
It seems to be ok, but when I evaluate, for example, from 1 to 10 (N=10) it should return 1 2 3 5 7 but instead this happens: 1 2 3 4 5

2 个评论

I recommend you rewrite the second function in terms of intersect()
[1] take a look at the statement A = [A,n].
[2] the restriction of p to <= 10 seems a bit artificial since it limits the number of primes you can get on output.

请先登录,再进行评论。

回答(1 个)

David Goodmanson
David Goodmanson 2016-9-17

0 个投票

(I guess my previous comment might be considered an answer). Take a look at the statement A = [A, n] which is not what you intended, and after you correct that it works great. However, restricting p to <=10 (something you did temporarily?) limits the number of primes you can produce to those <= 7. Also, it's kind of pedantic to bring it up, but 1 is not a prime.

类别

帮助中心File Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by