此素数生成方法如何工作? [英] How does this prime number generation method work?

查看:81
本文介绍了此素数生成方法如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚这段代码的背景是什么,具体地说,就是编写命令的原因.我了解所有内容,直到for循环的第一行,但随后我迷失了第二行:

I want to figure out what the background of this code is, specifically, the reason of the commands written. I understand everything until the first line of the for loop, but then I got lost with the second line:

N= input('Enter your number: ');

primes = 2:N;
p=2;

while (p <= N)
    for i = 2*p:p:N
        primes(i - 1) = 0;
    end;
    p = p + 1;
end

primes = primes(primes > 0)

有人可以帮助我理解此代码吗?

Can someone help me to understand this code please?

推荐答案

代码实现了勘误筛网查找素数.

它生成了数组primes,其中包含2 to N

It generated the array primes which contains the integer numbers from 2 to N

primes = 2:N

while循环遍历整数值

while (p <= N)

for循环中while循环的每次迭代中,p的当前值的倍数都是在循环索引变量i

At each iteration of the while loop in the for loop, the multiples of the current value of p are generated within the definition of the set of values of the loop index variable i

2*p:p:N

for循环的每次迭代中,将i位置中的primes数组的元素设置为0

at each iteration of the for loop the element of the primes array in the position i is set to 0

for循环的末尾,所有p的当前值的倍数都设置为0

At the end of the for loop, all the multiples of the current value of p are then set to 0

primes(i - 1) = 0;

然后通过while循环对2N之间的所有integers值重复该过程.

The process is then repeated for all the integers values between 2 and N by the while loop.

while循环的末尾,数组primes将包含2N之间的质数.

At the end of the while loop the array primes will contains the prime numbers between 2 and N.

primes = primes(primes > 0)

此指令在数组primes中查找与0不同的数字,并通过向其分配所有与0或相同的数字来重新定义数组本身.它将所有数组0从数组primes中删除.

This instruction finds the numbers different from 0 in the array primes and re-defines the array itself by assigning to it all all the numbers different from 0 or, that is the same. it removes from the array primes all of the 0s.

根据定义,给定数字的倍数不是质数.

By definition the multiple of a given number is not a prime number.

希望这会有所帮助.

这篇关于此素数生成方法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆