此素数生成方法如何工作? [英] How does this prime number generation method work?
问题描述
我想弄清楚这段代码的背景是什么,具体地说,就是编写命令的原因.我了解所有内容,直到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
循环对2
和N
之间的所有integers
值重复该过程.
The process is then repeated for all the integers
values between 2
and N
by the while
loop.
在while
循环的末尾,数组primes
将包含2
和N
之间的质数.
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 0
s.
根据定义,给定数字的倍数不是质数.
By definition the multiple of a given number is not a prime number.
希望这会有所帮助.
这篇关于此素数生成方法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!