zoukankan      html  css  js  c++  java
  • Count Primes 解答

    Question

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

    Solution 1

    Naive way, to check each number one by one. If a number i is prime, then for x from o to (i - 1), i % x != 0. Time complexity O(n^2).

    Solution 2

    Sieve of Eratosthenes 算法:

    由于一个合数总是可以分解成若干个质数的乘积,那么如果把质数(最初只知道2是质数)的倍数都去掉,那么剩下的就是质数了。
    例如要查找100以内的质数,首先2是质数,把2的倍数去掉;此时3没有被去掉,可认为是质数,所以把3的倍数去掉;再到5,再到7,7之后呢,因为8,9,10刚才都被去掉了,而100以内的任意合数肯定都有一个因子小于10(100的开方),所以,去掉,2,3,5,7的倍数后剩下的都是质数了。

     1 public class Solution {
     2     public int countPrimes(int n) {
     3         if (n <= 2)
     4             return 0;
     5         boolean[] primes = new boolean[n];
     6         primes[0] = false;
     7         for (int i = 2; i < n; i++) primes[i] = true;
     8         for (int i = 2; i < Math.sqrt(n); i++) {
     9             if (primes[i] == true) {
    10                 int j = 2;
    11                 while (i * j < n) {
    12                     primes[i * j] = false;
    13                     j++;
    14                 }
    15             }
    16         }
    17         int result = 0;
    18         for (int i = 2; i < n; i++) {
    19             if (primes[i])
    20                 result++;
    21         }
    22         return result;
    23     }
    24 }
  • 相关阅读:
    jQuery实现“回到顶部”按钮功能
    围绕DOM元素节点的增删改查
    jQuery ajax
    对JSON的理解
    Replacing Accented characters(Diacritic) .NET
    全球主要城市经纬度api
    无标题
    Use Razor for Email Template outside ASP.NET MVC
    .NET and php
    knockoutjs
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4806108.html
Copyright © 2011-2022 走看看