Leetcode#204count Primes

Source: Internet
Author: User

public class Solution {

public int countprimes (int n) {

int c=0;

if (n<=1)

return C;

else{

for (int j=2;j<=n;j++)

{

int v=0;

for (int i=2;i<=math.sqrt (n); i++)

{

if (j%i==0)

{

V=1;

Break

}

}

if (v==0)

C + +;

}

return C;

}

}

}

Show after submitting algorithm

Status:time Limit exceeded

Submitted: 0 minutes ago

Last executed input: 1500000

Modify

1. Calculates the number of mass that is less than N, except 2, in which all the even numbers are not prime, so they only judge all the odd

2. For an odd k, determine whether it is a prime number and only consider whether K is divisible by the value in 2~sqrt (k)

3. Because it is an odd number, it only determines whether it is divisible by the odd number in 2~sqrt (k).


public class Solution {

public int countprimes (int n) {

int c=0;

if (n<=2)

return C;

if (n==3)

return ++c;

else{

C + +;

for (int j=3;j<n;j=j+2)

{

int v=0;

for (int i=3;i<=math.sqrt (j); i=i+2)

{

if (j%i==0)

{

V=1;

Break

}

}

if (v==0)

C + +;

}

return C;

}

}

}


Leetcode#204count Primes

Related Article

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.