更新时间:2023-11-28 14:18:16
摆脱 cat
命令.这太贵了.有了它,我得到了 384239.返回质数向量反而让我得到了 471617,这是一个显着的改进.
Get rid of the cat
command. That's expensive. With it in place, I get to 384239. Returning the vector of primes instead gets me to 471617, a significant improvement.
改变 n >sqrt(counter)
到 n*n >counter
让我得到 477163,一个小小的改进.
Changing n > sqrt(counter)
to n*n > counter
gets me to 477163, a small improvement.
将 p_nums
和 counter
更改为 integer
类型使我得到 514859,这是另一个小改进.这是通过修改定义和调整这些行的行来实现的:
Changing p_nums
and counter
to be of type integer
gets me to 514859, another small improvement. This is achieved by modifying the lines where these are defined and adjusted:
p_nums = c(2L)
counter = 2L
# ... and inside the loop:
counter = counter +1L
请注意,您可以使用如下代码对确定某个值为素数的循环进行矢量化:
Note that you can vectorize the loop which determines that a value is prime, with code such as this:
isPRIME = !any(0 == (counter %% p_nums[1:sqrt(counter)]))
使用它代替 for
让我得到 451249,这是一个显着的回归(不使用 cat
并使用整数算法).这是因为 R 没有惰性列表评估,所以对每个值都取模数,然后对 0 进行测试.在这种情况下,这是 for
的一个优点.
Using that instead of for
gets me to 451249, a significant regression (using no cat
and using integer arithmetic). This is because R does not have lazy list evaluation, so the modulus is taken for every value, then they are tested against 0. This is an advantage of for
in this case.