鱼C论坛

 找回密码
 立即注册
查看: 1642|回复: 0

[学习笔记] leetcode 204. Count Primes

[复制链接]
发表于 2019-9-15 00:04:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

  2. Example:

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

  1. class Solution {
  2.     public int countPrimes(int n) {
  3.         if(n <= 1) return 0;
  4.         
  5.         boolean[] arr = new boolean[n];
  6.         arr[0] = true;
  7.         arr[1] = true;
  8.         
  9.         for(int i = 2; i < Math.sqrt(n) ; i++){
  10.             if(arr[i] == false){
  11.                
  12.                 for(int j = 2 ; j*i < n; j++){
  13.                
  14.                     arr[i*j] = true;
  15.                 }
  16.             }
  17.             
  18.         }
  19.         int count = 0;
  20.         
  21.         for(int i = 2; i< arr.length; i++){
  22.             
  23.             if(!arr[i]) count++;
  24.         }
  25.         
  26.         return count;
  27.     }
  28.    
  29. }
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-7 12:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表