Prime Function without Conditionals or Iteration

1 次查看(过去 30 天)
I have to construct a code that inputs a positive integer N and outputs a vector of the prime numbers up to that positive integer N. I know you have to eliminate the multiples of 2, then then the multiples of 3, and so on until you get to floor(sqrt(N)). However, I'm having trouble in translating this into code. The following functions are banned:
primes(), isPrime(), ismember(), setdiff(), factor()
function [out] = sieve(N)
limit = floor(sqrt(N));
vec = 1:limit
mask =
I'm stuck trying to make a mask for the vector.

回答(2 个)

Walter Roberson
Walter Roberson 2017-2-6
You can use ndgrid to construct matrices of values, and mod() to test whether one value divides another. The results that are 0 are the places where one value divides another. But watch out for the fact that a value divides itself.

KSSV
KSSV 2017-2-6
clc; clear all ;
N = 10 ;
p = primes(N) ;
c = 0 ;
for n = 2:N
m = 2; % initialise factor to test
t=floor(sqrt(n));count=0;
for m = 2:t
if mod(n,m) == 0 %m is a factor of n
fprintf('%d is not prime \n',n)
primalitytest=0;
else
count=count+1;
end
end;
if count==t-1
fprintf(' %d is prime\n',n);
primalitytest=1;
c = c+1 ;
iwant(c) = n ;
end
end

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by