What is wrong with my code?
Show older comments
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 Comments
Walter Roberson
on 13 Sep 2016
David Goodmanson
on 17 Sep 2016
[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.
Answers (1)
David Goodmanson
on 17 Sep 2016
0 votes
(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.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!