zoukankan      html  css  js  c++  java
  • leetcode 204 计数质数

    package com.example.lettcode.dailyexercises;
    
    /**
     * @Class CountPrimes
     * @Description 204 计数质数
     * 统计所有小于非负整数 n 的质数的数量。
     * <p>
     * 示例 1:
     * 输入:n = 10
     * 输出:4
     * 解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
     * 示例 2:
     * 输入:n = 0
     * 输出:0
     * <p>
     * 示例 3:
     * 输入:n = 1
     * 输出:0
     * <p>
     * 提示:
     * 0 <= n <= 5 * 106
     * 哈希 数学
     * @Author
     * @Date 2020/12/3
     **/
    public class CountPrimes {
        public static int countPrimes(int n) {
            if (n <= 1) return 0;
            boolean[] isPrime = new boolean[n];
            int res = 0;
            for (int i = 2; i < n; i++) {
                isPrime[i] = true;
            }
            // i*i
            for (int i = 2; i*i < n; i++) {
                if (!isPrime[i]) continue;
                //由于i现在是一个质数, 那么i的平方一定不是质数,i^2 + i; i^2 + 2i也一定不是素数
                for (int j = i * i; j < n; j += i) {
                    isPrime[j] = false;
                }
            }
            for (int i = 2; i < n; i++) {
                if(isPrime[i]) res++;
            }
            return res;
        }
    
    
    
    
        public static void main(String[] args) {
            int n = 10;
            int ans = countPrimes(n);
            System.out.println("CountPrimes demo01 result: " + ans);
    
            n = 0;
            ans = countPrimes(n);
            System.out.println("CountPrimes demo02 result: " + ans);
    
            n = 1;
            ans = countPrimes(n);
            System.out.println("CountPrimes demo03 result: " + ans);
    
            n = 3;
            ans = countPrimes(n);
            System.out.println("CountPrimes demo04 result: " + ans);
    
            n = 13;
            ans = countPrimes(n);
            System.out.println("CountPrimes demo04 result: " + ans);
    
            n = 499979;
            ans = countPrimes(n);
            System.out.println("CountPrimes demo04 result: " + ans);
        }
    }
    
  • 相关阅读:
    python is == 区别
    python 元类 type metaclass
    树莓派 zero w 一根线使用
    python 类装饰器
    Oracle创建用户
    hibernate使用原生SQL查询
    工作流 jBMP4.4表结构
    (Mark)Myeclipse10.6 下怎么安装Jad插件
    (Mark=转)ehcache memcache redis
    Oracle 常用命令
  • 原文地址:https://www.cnblogs.com/fyusac/p/14082705.html
Copyright © 2011-2022 走看看