leetcode--Count Primes

来源:互联网 发布:知乎 显微镜原理 编辑:程序博客网 时间:2024/06/06 03:11

Description:

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

[java] view plain copy
  1. public class Solution {  
  2.     public int countPrimes(int n) {  
  3.         if(n<2return 0;  
  4.         boolean[] flag = new boolean[n+1];  
  5.         int count = 0;  
  6.         for(int i=2;i<n;i++){  
  7.             if(!flag[i]){//如果是质数,则将其倍数设置为非质数  
  8.                 for(int j=2;i*j<=n;j++){  
  9.                     flag[i*j] = true;  
  10.                 }  
  11.             }  
  12.         }  
  13.         for(int i=2;i<n;i++){  
  14.             if(!flag[i]) count++;  
  15.         }  
  16.         return count;  
  17.     }  
  18. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/45440035

原创粉丝点击