Prime Function without Conditionals or Iteration

조회 수: 3 (최근 30일)
Eduardo Alfaro
Eduardo Alfaro 2017년 2월 6일
댓글: Eduardo Alfaro 2017년 2월 6일
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
  댓글 수: 1
Eduardo Alfaro
Eduardo Alfaro 2017년 2월 6일
I'm not allowed to use any iteration or conditionals.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by