フィルターのクリア

Prime Function without Conditionals or Iteration

1 回表示 (過去 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 Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by