1. Title
Count Primes (count number of prime numbers)
2. Address of the topic
https://leetcode.com/problems/count-primes/
3. Topic content
English: Count The number of prime numbers less than a non-negative number, N.
English: Count the number of prime numbers within a positive integer n (excluding n itself)
4, a method of tle
From 1 to N, examine whether each number is prime. This method can not meet the requirement of time in the problem because it takes a long time.
A section of Java code that implements this method is as follows:
/** * function Description:leetcode 204 - count primes * developer:tsybius2014 * Development Date: September 6, 2015 */public class solution { /* * * calculates the number of prime numbers below n * @param n positive integers * @return Number of prime numbers below n */ public int countprimes (int n) { if (n <= 1) { return 0; } int result = 0; boolean isprime = true; for (int i = 2; i < n; i++) { //Judging whether the number I is prime isPrime = true; if (i == 2 | | i == 3 | | i == 5 | | &NBSP;I&NBSP;==&NBSP;7) { isPrime = true; } else if (i % 2 == 0 | | i % 3 == 0 | | i % 5 == 0 | | i % 7 == 0) { isprime = false; } else { for (int j = 2; j <=&NBSP;MATH.SQRT (i); j++) { if (i % j == 0) { isPrime = false; break; } } } //If I is prime number result self-increment 1 if (IsPrime) { result++; } } return result; }}
4. Methods of Solving problems
Another method for prime numbers is the Eratosthenes sieve method (Sieve of Eratosthenes), which needs to declare a very large array, but at a much faster speed than the above method.
A section of Java code that implements this method is as follows:
/** * function Description:leetcode 204 - count primes * developer:tsybius2014 * Development Date: September 6, 2015 */public class solution { /* * * calculates the number of prime numbers below n * @param n positive integers * @return Number of prime numbers below n */ public int countprimes (int n) { if (n <= 1) { return 0; } int result = 0; boolean[] arr = new boolean[n]; for (INT&NBsp;i = 2; i < n; i++) { //if Arr[i] is a prime number that marks all multiples as composite, otherwise it is not considered if (!arr[i] ) { result ++; } else { continue; } int j = 2; while (i * j < n) { arr[i * j] = true; j++; } } return result; }}
END
Leetcode:count Primes-Statistics number of prime numbers