LEETCODE,[LeetCode] 204. Count Primes

 2023-11-05 阅读 28 评论 0

摘要:204.?Count Primes Count the number of prime numbers less than a non-negative number,?n. Example: Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.題意:找素數,找n以內有多少個素數篩數法統計 class So

204.?Count Primes



Count the number of prime numbers less than a non-negative number,?n.

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.


題意:找素數,找n以內有多少個素數
篩數法統計
class Solution {public int countPrimes(int n){if (n == 0 || n == 1 || n == 2)return 0;int[] num = new int [n];for (int i = 0; i < n; i++) {num[i] = i;}for (int i = 2; i < n; i++) {if (num[i] != 0) {for (int j = 2; j*i < n; j ++)num[j*i] = 0;}}int sum = 0;for (int i = 0; i < n; i++) {if (num[i] != 0)sum ++;}return sum - 1;}
}

最快的算法應該是 6n那個,但是我不會,hhaha有興趣的小伙伴可以自學一下

轉載于:https://www.cnblogs.com/Moriarty-cx/p/9704231.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/166366.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息