【问题标题】:Matlab Prime number list checkerMatlab素数列表检查器
【发布时间】:2016-08-18 12:30:53
【问题描述】:

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

#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。

【问题讨论】:

  • 这是 1) 好玩吗? 2)上课? 3)或者你真的需要一个质数检查器?
  • 只是为了好玩 :) 努力在大学重新开始之前在 matlab 上变得更好!
  • 提高效率的小窍门:如果一个数字不能被 2 整除,那么它就不会是 4、6、8...,因此您可以大大减少检查次数。同样适用于 3、6、9 等...
  • 为什么不直接使用isprime
  • 感谢Sembei,我会努力实现它。

标签: matlab for-loop


【解决方案1】:

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

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

【讨论】:

  • 您好 obchardon,感谢您的代码。首先,矩阵是如何工作的? (当我将它放入matlab时看起来很有趣),我将它放入我之前的内容中。它可以找到很多素数。但我也得到了一些误报,比如 4、8、16、64。上面的代码中没有包含 4 吗?这就是我使用的 [code] prompt = input("要测试的最大数量:"); n = 提示;对于 i = 2:n t1 = i./(3:2:i/2); t2 = t1 - 回合(t1); res = find(t2 == 0,1); %n 可以除吗? if size(res,2) == 0 prime = sprintf('%d is prime', round(i)); disp(prime) end end [/code]
  • @JamesBlackwell 呵呵,我的错,我没有检查测试号是否是偶数,现在它已修复:) 与您的算法相似,我只是检查测试号是否可以除以 [2,3,5,7,9,11... n/2]。使用 ./ 运算符,您可以在 Matlab 中将单个数字除以数组,然后代码只检查它是否存在没有休息的除法。
  • 非常感谢您的帮助!我会投票,但仍然需要先增加我的代表。这是一种非常干净的检查方式:)
【解决方案2】:

我在这个问题上得到了帮助,发现“计数器”一直在重新设置,需要向上移动。固定代码在这里

#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

【讨论】:

    猜你喜欢
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多