For loop will slow down if it have to repeat many times?

I have coded a solution to solve the problem on this site:
http://www.codechef.com/problems/INTEST

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int main()
{
   unsigned int n, k, in, out = 0;
   cin >> n >> k;
   for (int i = 0; i < n; i++) {
       cin >> in;
       out += (in % k == 0);
   }
   
   cout << out;
   return 0;
}


I submitted the solution but it exceeded the time limit.
Here's my questions:
• If the input was "7 3" , would n equal 7 and k equal 3?
• Is there anyway that make the solution run faster, anything that can replace(can be used instead of) the for loop to make the solution run faster?

(I think the input assigned to n had to be a really big number so the for loop repeated so many times that the solution ran so slow)

P/s: Sorry for my English if it's hard to understand.
Last edited on
C++ streams are way slower than C ones. Do not use them when speed is critical and errors are unlikely. You can use scanf to read values in a loop. (you can leave other unchanged if you want, they do not use much time)
1
2
3
int main()
{
   std::ios_base::sync_with_stdio(false); // http://codeforces.com/blog/entry/925 


> C++ streams are way slower than C ones
no, they are not
Last edited on
sync_with_stdio
Sadly its effects implementation defined and as article states does not make much difference for VS.

no, they are not

Strange, I always thought that all those sentries constructing, checking states and more layers of indirection should impact perfomance. However graphs in your article shows that it is even faster than C output.

Do you have links to articles discussing this and maybe other tricks to streams?
Thanks guys, all I did was adding
1
2
ios_base::sync_with_stdio(false);
cin.tie(NULL);


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
 
using namespace std;
 
int main()
{
   ios_base::sync_with_stdio(false);
   cin.tie(NULL);
   
   unsigned int n, k, in, out = 0;
   cin >> n >> k;
   for (int i = 0; i < n; i++) {
       cin >> in;
       out += (in % k == 0);
   }
   
   cout << out;
   return 0;
}


but the execution time was 4.42 seconds.
Last edited on
Topic archived. No new replies allowed.