Matlab Prime数字列表检查器

时间:2016-08-18 12:30:53

标签: matlab for-loop

好的,所以我一直在创建一个素数检查器。我成功地使它适用于特定的数字。代码在这里。

#To test if number is prime

prompt = input("number to test if prime: ");
n = prompt;
i = 2; #start of mod test
t = floor(sqrt(n));
counter = 0;
tic
for i = 2:t
  if mod(n,i) == 0 
    disp('n is not prime')
    break
  else
    counter = (counter + 1);
  end
end

if counter == t-1
  disp('n is prime')
end
toc

然后我尝试制作一个测试一系列数字的程序。它已经成功了n = 10,但是当我高于它时它似乎没有拿起素数。我不确定我哪里出错了。

#Want to test numbers 2:n if they're prime

prompt = input("max number to test: ");
n = prompt;
l = 2; #start of mod test
counter = 0;
tic

for i = 2:n #cycle to test 2 up to n
  t = floor(sqrt(i)) #Only need to test up to root of number
  for l = 2:t
    if mod(i,l) == 0 
      break
    else
      counter = (counter + 1);
      end
  end
  if counter == t-1 # if tested up to the root of the number, it must be prime
    prime = sprintf('%d is prime', round(i));
    disp(prime)
    counter = 0;
  end
end
toc

任何有助于使其适用于更大值的帮助都将非常受欢迎,并且还有任何方法可以使代码更有效。顶级程序可以在我的笔记本电脑上在0.268秒内测试982451653。

2 个答案:

答案 0 :(得分:0)

只是一种线性化算法的方法:

n = 997 %test number
t1 = n./([2,3:2:n/2]);
t2 = t1 - round(t1);
res = sum(t2 == 0); %can n be divided ? 

if res == 0
    fprintf('%s','prime');
else
    fprintf('%s','not prime');
end

答案 1 :(得分:0)

我在这个问题上获得了帮助,并发现“计数器”不断重新设置,需要提升。固定代码在这里

#Want to test numbers 2:n if they're prime

prompt = input("max number to test: ");
n = prompt;
l = 2; #start of mod test
counter = 0;
tic

for i = 2:n #cycle to test 2 up to n
  t = floor(sqrt(i)); #Only need to test up to root of number
  counter = 0;
  for l = 2:t
    if mod(i,l) == 0 
      break
    else
      counter = (counter + 1);
      end
  end
  if counter == t-1; # if tested up to the root of the number, it must be prime
    prime = sprintf('%d is prime', round(i));
    disp(prime)

  end
end
toc