给定两个正整数N和K ,任务是计算三元组(a,b,c)的数量,以使0 和(a + b) , (b + c)和(c + a)都是K的倍数。
例子:
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
天真的方法:有关解决此问题的最简单方法,请参阅上一篇文章。
时间复杂度: O(N 3 )
辅助空间: O(1)
高效方法:还可以基于以下观察来优化上述方法:
- 给定条件由等式表示:
=> a + b ≡ b + c ≡ c + a ≡ 0(mod K)
=> a+b ≡ b+c (mod K)
=> a ≡ c(mod K)
- 不使用等式,也可以观察到上述关系:
- 由于(a + b)是K的倍数,而(c + b)是K的倍数。因此, (a + b)−(c + b)= a – c也是K的倍数,即a≡b≡c(mod K) 。
- 因此,可以将该表达式进一步评估为:
=> a + b ≡ 0 (mod K)
=> a + a ≡ 0 (mod K) (since a is congruent to b)
=> 2a ≡ 0 (mod K)
根据以上观察结果,可以计算出以下两种情况的结果:
- 如果K是奇数,则a b b c c 0(mod K),因为所有这三个都是一致的,并且三元组的总数可以计算为(N / K) 3 。
- 如果K为偶数,则K可被2除以a≡0(模K) , b≡0(模K)和c≡0(模K) 。因此,三元组的总数可以计算为(N / K) 3 ((N +(K / 2))/ K) 3 。
下面是上述方法的实现:
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 K
int 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 Code
int main()
{
int N = 2, K = 2;
cout << countTriplets(N, K);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG{
// Function to count the number of
// triplets from the range [1, N - 1]
// having sum of all pairs divisible by K
static int countTriplets(int N, int K)
{
// If K is even
if (K % 2 == 0)
{
int x = N / K;
int y = (N + (K / 2)) / K;
return x * x * x + y * y * y;
}
// Otherwise
else
{
int x = N / K;
return x * x * x;
}
}
// Driver Code
public static void main(String[] args)
{
int N = 2, K = 2;
System.out.print(countTriplets(N, K));
}
}
// This code is contributed by Kingash
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 K
def 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 Code
if __name__ == "__main__":
N = 2
K = 2
print(countTriplets(N, K))
# This code is contributed by ukasp
Javascript
输出:
2
时间复杂度: O(1)
辅助空间: O(1)