Monday, April 5, 2021

Published April 05, 2021 by Anonymous with 0 comment

Count triplets (a, b, c) such that a + b, b + c and a + c are all divisible by K | Set 2

Count triplets (a, b, c) such that a + b, b + c and a + c are all divisible by K | Set 2

Given two positive integers N and K, the task is to count the number of triplets (a, b, c) such that 0 < a, b, c < N and (a + b), (b + c) and (c + a) are all multiples of K.

Examples:

Input: N = 2, K = 2
Output: 2
Explanation: All possible triplets that satisfy the given property are (1, 1, 1) and (2, 2, 2).
Therefore, the total count is 2.

Input: N = 3, K = 2
Output: 9

Naive Approach: Refer to the previous post for the simplest approach to solve this problem.
Time Complexity: O(N3)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized based on the following observations:

  • The given condition is expressed by a congruence formula:

=> a + b ≡ b + c ≡ c + a ≡ 0(mod K)
=> a+b ≡ b+c (mod K)
=> a ≡ c(mod K)

  • The above relation can also be observed without using the congruence formula as:
    • As (a + b) is a multiple of K and (c + b) is a multiple of K. Therefore, (a + b) − (c + b) = a – c is also a multiple of K, i.e., a ≡ b ≡ c (mod K).
    • Therefore, the expression can be further evaluated to:

=> a + b ≡ 0 (mod K)
=> a + a ≡ 0 (mod K) (since a is congruent to b)
=> 2a ≡ 0 (mod K)


From the above observations, the result can be calculated for the following two cases:

  • If K is odd, then a ≡ b ≡ c ≡ 0(mod K) since all three are congruent and the total number of triplets can be calculated as (N / K)3.
  • If K is even, then K is divisible by 2 and a ≡ 0 (mod K), b ≡ 0 (mod K), and c ≡ 0 (mod K). Therefore, the total number of triplets can be calculated as (N / K)3 ((N + (K/2)) / K)3.

Below is the implementation of the above approach:

C++

  

#include "bits/stdc++.h"

using namespace std;

  

int countTriplets(int N, int K)

{

    

    if (K % 2 == 0) {

        long long int x = N / K;

        long long int y = (N + (K / 2)) / K;

  

        return x * x * x + y * y * y;

    }

  

    

    else {

        long long int x = N / K;

        return x * x * x;

    }

}

  

int main()

{

    int N = 2, K = 2;

    cout << countTriplets(N, K);

  

    return 0;

}

Time Complexity: O(1)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Let's block ads! (Why?)


Original page link

Best Cool Tech Gadgets

Top favorite technology gadgets
      edit

0 comments:

Post a Comment