< Back to forum

How can I solve this problem in the given link without using nested loop???

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.


Enter your answer details below:


Enter your comment details below:




1 Answer(s)

avatar

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)
 

Shubham_Kumar_Gupta last updated on April 7, 2019, 6:34 p.m. 1    Reply    Upvote   

Instruction to write good question
  1. 1. Write a title that summarizes the specific problem
  2. 2. Pretend you're talking to a busy colleague
  3. 3. Spelling, grammar and punctuation are important!

Bad: C# Math Confusion
Good: Why does using float instead of int give me different results when all of my inputs are integers?
Bad: [php] session doubt
Good: How can I redirect users to different pages based on session data in PHP?
Bad: android if else problems
Good: Why does str == "value" evaluate to false when str is set to "value"?

Refer to Stack Overflow guide on asking a good question.