简体   繁体   中英

Time Limit Exceeded - Simple Program - Divisibility Test

Input The input begins with two positive integers nk (n, k<=10^7). The next n lines of input contain one positive integer ti, not greater than 10^9, each.

Output Write a single integer to output, denoting how many integers ti are divisible by k.

Example

Input:

7 3
1
51
966369
7
9
999996
11

Output:

4

My Code:

#include <iostream>
using namespace std;

int main()
{


long long n,k, i;
cin>>n;
cin>>k;
int count=0;
for(i=0;i<n;i++)
{
    int z;
    cin>>z;
    if(z%k == 0) count++;
}
cout<<count;

return 0;
}

Now this code produces the correct output. However, its not being accepted by CodeChef( http://www.codechef.com/problems/INTEST ) for the following reason: Time Limit Exceeded. How can this be further optimized?

As said by caleb the problem is labeled " Enormous Input Test " so it requires you to use some better/faster I/O methods

just replacing cout with printf and cin with scanf will give you an AC but to improve your execution time you need to use some faster IO method for example reading character by character using getchar_unlocked() will give you a better execution time

so you can read the values by using a function like this , for a better execution time.

 inline int read(){
    char c=getchar_unlocked();
    int n=0;
    while(!(c>='0' && c<='9'))
     c=getchar_unlocked();
    while(c>='0' && c<='9'){
     n=n*10 + (c-'0');
    c=getchar_unlocked();
}
return n;
}

The linked problem contains the following description:

The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime.

Considering that, reading values from input a few bytes at a time using iostreams isn't going to cut it. I googled around a bit and found a drop-in replacement for cin and cout described on CodeChef . Some other approaches you could try include using a memory-mapped file and using stdio.

It might also help to look for ways to optimize the calculation. For example, if t i < k, then you know that k is not a factor of t i . Depending on the magnitude of k and the distribution of t i values, that observation alone could save a lot of time.

Remember: the fact that your code is short doesn't mean that it's fast .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM