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++
// C++ program for the above approach#include "bits/stdc++.h"using namespace std;// Function to count the number of// triplets from the range [1, N - 1]// having sum of all pairs divisible by Kint countTriplets(int N, int K){ // If K is even 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; } // Otherwise else { long long int x = N / K; return x * x * x; }}// Driver Codeint main(){ int N = 2, K = 2; cout << countTriplets(N, K); return 0;} |
Python3
# Python3 program for the above approach# Function to count the number of# triplets from the range [1, N - 1]# having sum of all pairs divisible by Kdef countTriplets(N, K): # If K is even if (K % 2 == 0): x = N // K y = (N + (K // 2)) // K return x * x * x + y * y * y # Otherwise else: x = N // K return x * x * x# Driver Codeif __name__ == "__main__": N = 2 K = 2 print(countTriplets(N, K))# This code is contributed by ukasp |
2
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.



