zoukankan      html  css  js  c++  java
  • leetcode 204. Count Primes 找出素数的个数 ---------- java

    Description:

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

    找出小于n的素数个数。

    1、用最淳朴的算法果然超时了。

    public class Solution {
        public int countPrimes(int n) {
            if (n < 2){
                return 0;
            }
            int result = 0;
            for (int i = 2; i < n; i++){
                if (isPrimes(i)){
                    result++;
                }
            }
            return result;
        }
        public boolean isPrimes(int num){
            for (int i = 2; i <= Math.sqrt(num); i++){
                if (num % i == 0){
                    return false;
                }
            }
            return true;
        }
    }

    2、埃拉托斯特尼筛法Sieve of Eratosthenes

    我们从2开始遍历到根号n,先找到第一个质数2,然后将其所有的倍数全部标记出来,然后到下一个质数3,标记其所有倍数,一次类推,直到根号n,此时数组中未被标记的数字就是质数。我们需要一个n-1长度的bool型数组来记录每个数字是否被标记,长度为n-1的原因是题目说是小于n的质数个数,并不包括n。

    public class Solution {
            public int countPrimes(int n) {
                boolean[] isPrime = new boolean[n];
                for (int i = 2; i < n; i++) {
                    isPrime[i] = true;
                }
                for (int i = 2; i * i < n; i++) {
                    if (!isPrime[i]) continue;
                    for (int j = i * i; j < n; j += i) {
                        isPrime[j] = false;
                    }
                }
                int count = 0;
                for (int i = 2; i < n; i++) {
                    if (isPrime[i]) count++;
                }
                return count;
            }
        }
  • 相关阅读:
    Hello_Area_Description 任务三:Project Tango采集区域描述数据
    智能小车 机器人
    Hello_Depth_Perception 任务二:Project Tango采集深度感知数据
    Project Tango Explorer
    make运行阶段划分
    关于chroot
    xargs命令
    debian配置集锦
    gdb使用技巧
    gdb调试使用autotools工程的项目
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6612699.html
Copyright © 2011-2022 走看看