I am new to competitive coding (C++) and was Practising on hackerEarth problems based on Implementation . I submitted a problem to find summations of an array in 3 diff. parts . Here's My code it took 1.010039s to execute:
int main()
{
long unsigned int n, a[100000], s1 = 0, s2 = 0, s3 = 0;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
if (i % 3 == 0)
s3 = s3 + a[i];
else if ((i - 2) % 3 == 0)
s2 = s2 + a[i];
else
s1 = s1 + a[i];
}
cout << s1 << " " << s2 << " " << s3;
return 0;
}
Here's The Least Time code :
int main()
{
int n;
long unsigned int a[100000];
long unsigned int s1 = 0, s2 = 0, s3 = 0;
int i;
cin >> n;
for (i = 0; i < n; i++) {
cin >> a[i];
}
for (i = 0; i < n; i = i + 3) {
s1 = s1 + a[i];
}
for (i = 1; i < n; i = i + 3) {
s2 = s2 + a[i];
}
for (i = 2; i < n; i = i + 3) {
s3 = s3 + a[i];
}
cout << s1 << " " << s2 << " " << s3 << endl;
return 0;
}
we can see that ,there are much more for loops in the second case , and still it is faster why ?