Leetcode 204. Count Primes Find the number of primes----------Java

Source: Internet
Author: User
Tags square root

Description:

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

Find the number of characters less than N.

1, with the most simple algorithm is timed out.

 Public classSolution { Public intCountPrimes (intN) {if(N < 2){            return0; }        intresult = 0;  for(inti = 2; I < n; i++){            if(Isprimes (i)) {result++; }        }        returnresult; }     Public BooleanIsprimes (intnum) {         for(inti = 2; I <= math.sqrt (num); i++){            if(num% i = = 0){                return false; }        }        return true; }}

2, Eratosthenes sieve method Sieve of Eratosthenes

We go from 2 to the square root N, find the first prime number 2, and then all of its multiples are marked out, then to the next prime number 3, mark all its multiples, once and so, until the square root of N, when the array is not marked with numbers is prime. We need a n-1-length bool array to record whether each number is marked, and the length is n-1 because the topic is said to be less than N of the mass number, not including N.

 Public classSolution { Public intCountPrimes (intN) {Boolean[] IsPrime =New Boolean[n];  for(inti = 2; I < n; i++) {Isprime[i]=true; }             for(inti = 2; I * i < n; i++) {                if(!isprime[i])Continue;  for(intj = i * I; J < N; J + =i) {isprime[j]=false; }            }            intCount = 0;  for(inti = 2; I < n; i++) {                if(Isprime[i]) count++; }            returncount; }    }

Leetcode 204. Count Primes Find the number of primes----------Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.