Prime Function without Conditionals or Iteration
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Antworten (2)
Walter Roberson
am 6 Feb. 2017
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.
0 Kommentare
KSSV
am 6 Feb. 2017
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
Siehe auch
Kategorien
Mehr zu Performance and Memory finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!