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;
}