Jan 09-count Primes; Mathematics; optimization; Primes; DP;

Source: Internet
Author: User
Tags log log

The first method of the Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to N.

The Sieve of Eratosthenes uses an extra O (n) memory and their runtime complexity is O (n log log n )

Creates a Boolean array of length = N IsPrime, with each element initialized to true;

K = 2: (n-1), if the current number k is the prime, put K^k-(n-1)/k *k of the number of pairs of mappings = false;

Finally, count from 2 to n-1 IsPrime = = True.

Code:

public class Solution {
public int countprimes (int n) {
boolean[] Isprimes = new Boolean[n];
for (int i = 0; i < isprimes.length; i++) {
Isprimes[i] = true;
}

for (int k = 2; k <= (n-1)/k; k++) {
if (isprimes[k] = = True) {
for (int i = k; I <= (n-1)/k; i++) {
Isprimes[i*k] = false;
}
}
}
int count = 0;
for (int i = 2; i< isprimes.length; i++) {
if (isprimes[i] = = true) count++;
}
return count;
}
}

You can also use DP to solve.

public class Solution {
public int countprimes (int n) {

int count = 0;
int squareroot = 1;
int number = 2;

list<integer> list = new arraylist<> ();
for (int i = number; i < n; i++) {
Boolean isprime = true;
if (SquareRoot * SquareRoot < i) squareroot++;
for (int j = 0; J < list.size () && List.get (j) <= squareroot;j++) {
if (I%list.get (j) = = 0) {
IsPrime = false;
Break
}
}
if (IsPrime = = True) {
List.add (i);
count++;
}
}
return count;
}
}

Runtime:o (N*SQRT (n)/log (n))

Finally, record the most primitive method of 0-sqrt (n):

public class Solution {
public int countprimes (int n) {

int count = 0;
int squareroot = 1;
int number = 2;

for (int i = number; i < n; i++) {
Boolean isprime = true;

for (int divisor = 2; divisor <= (int) (MATH.SQRT (i)); divisor++) {
if (I%divisor = = 0) {
IsPrime = false;
Break
}
}
if (IsPrime = = True) {
count++;
}
}
return count;
}
}

Jan 09-count Primes; Mathematics; optimization; Primes; DP;

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.