如何高效寻找素数 :: labuladong的算法小抄 #1082
Replies: 10 comments 2 replies
-
米青女少 ! |
Beta Was this translation helpful? Give feedback.
-
只更新每个合数最小的素数可以优化到O(n) |
Beta Was this translation helpful? Give feedback.
-
比如 n = 25,i = 4 时算法会标记 4 × 2 = 8,4 × 3 = 12 等等数字,但是这两个数字已经被 i = 2 和 i = 3 的 2 × 4 和 3 × 4 标记了。 |
Beta Was this translation helpful? Give feedback.
-
@Maschinist-LZY 嗯,你说得对,我大意了。把 |
Beta Was this translation helpful? Give feedback.
-
打卡,感谢楼主! |
Beta Was this translation helpful? Give feedback.
-
“首先,回想刚才判断一个数是否是素数的 isPrime 函数,由于因子的对称性,其中的 for 循环只需要遍历 [2,sqrt(n)] 就够了。这里也是类似的,我们外层的 for 循环也只需要遍历到 sqrt(n)”,没明白是怎么类似的?我个人觉得这里能优化成sqrt(n)的原因是内层循环的j被优化成从i^2开始,所以外层循环才可以被优化成sqrt(n),而不是因为因子对称性 |
Beta Was this translation helpful? Give feedback.
-
打卡。妙哉妙哉,排除法! |
Beta Was this translation helpful? Give feedback.
-
20230107 打卡,leetcode看到一个老哥对这种解法提了优化,时间复杂度beats 99% 主要优化点是内外层的for loop都只遍历奇数,确实速度快了一倍。。。 https://leetcode.com/problems/count-primes/solutions/57588/my-simple-java-solution/comments/210313 |
Beta Was this translation helpful? Give feedback.
-
给力,筛法确实猛 |
Beta Was this translation helpful? Give feedback.
-
可以借助Go的goroutine,进一步优化筛法
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
文章链接点这里:如何高效寻找素数
评论礼仪 见这里,违者直接拉黑。
Beta Was this translation helpful? Give feedback.
All reactions