Prime Number slot csuoj

Source: Internet
Author: User

Timeout code:

# Include <iostream>

Using namespace STD;
// Write a function to determine whether it is a prime number.
Bool isprime (INT num)
{Int I = 2; // cout <"ok2 ";
For (; I * I <= num; I ++ ){
If (Num % I = 0) break;
}
If (I * I> num) return true;
Else return false;
}


Int main ()
{

Int T;
Cin> T;

For (Int J = 1; j <= T; j ++ ){
Int aim;
Cin> aim;

Int COUNT = 2;

If (isprime (AIM )){

Cout <0 <Endl;
}
Else {
For (INT I = aim-1; I --) {If (isprime (I) break;
Else count ++ ;}
For (INT I = aim + 1; I ++) {If (isprime (I) break;
Else count ++ ;}

Cout <count <Endl;
}
}
Return 0;
}

The reason for timeout is that each time you determine whether it is a prime number separately, it cannot be processed when there are a large number of prime numbers.

Then the problem is solved by creating a large bool array.

AC code:

# Include <iostream>

Using namespace STD;

Bool * Zhangjie = new bool [1299710]; // The first operation is to apply for and allocate space.

 


Int main ()
{
For (INT p = 1; p <= 1299710; P ++ ){
Zhangjie [p] = true;
} // This Is An initialization operation.

For (INT I = 2; I <1299710; I = I + 1)
{
If (Zhangjie [I]) {
For (Int J = I + I; j <= 1299710; j = J + I)
Zhangjie [J] = false;
}
}
Int T;
Cin> T;

For (Int J = 1; j <= T; j ++ ){
Int aim;
Cin> aim;

Int COUNT = 2;

If (Zhangjie [aim]) {

Cout <0 <Endl;
}
Else {
For (INT I = aim-1; I --) {If (Zhangjie [I]) break;
Else count ++ ;}
For (INT I = aim + 1; I ++) {If (Zhangjie [I]) break;
Else count ++ ;}

Cout <count <Endl;
}
}
Return 0;
}

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.