Number of triplets such that each value is less than N and each pair sum is a multiple of K | C ++ implementation of the above approach ; Function to return the number of triplets ; Initializing the count array ; Storing the frequency of each modulo class ; If K is odd ; If K is even ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int NoofTriplets ( int N , int K ) { int cnt [ K ] ; memset ( cnt , 0 , sizeof ( cnt ) ) ; for ( int i = 1 ; i <= N ; i += 1 ) { cnt [ i % K ] += 1 ; } if ( K & 1 ) return cnt [ 0 ] * cnt [ 0 ] * cnt [ 0 ] ; else { return ( cnt [ 0 ] * cnt [ 0 ] * cnt [ 0 ] + cnt [ K / 2 ] * cnt [ K / 2 ] * cnt [ K / 2 ] ) ; } } int main ( ) { int N = 3 , K = 2 ; cout << NoofTriplets ( N , K ) ; return 0 ; }