http://hr.gs/4ottg
Its showing time out with nested loop
Asked by: Proma_Roy on April 7, 2019, 6:34 p.m. Last updated on April 7, 2019, 6:34 p.m.
The constraints in this problem are such that it can be solved using 2 nested loops. Optimization is not required.
For each i from from [0 , N - 1] we run a loop j from [i + 1, N - 1] and check the divisibility of each pair (i, j) and increase the count accordingly.
Code : (C++)
int n, k;
cin >> n >> k;
int arr[n];
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
int cnt = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if ((arr[i] + arr[j]) % k == 0) {
cnt++;
}
}
}
cout << cnt;
Complexity : O ( n * n)