Número de pares de los primeros N números naturales cuya suma es divisible por K

Dados los valores enteros de N y K . La tarea es encontrar el número de pares del conjunto de números naturales hasta N{1, 2, 3……N-1, N} cuya suma es divisible por K. 
Nota: 1 <= K <= N <= 10^6.
Ejemplos: 
 

Entrada : N = 10, K = 5 
Salida :
Explicación : Los posibles pares cuya suma es divisible por 5 son (1, 4), (1, 9), (6, 4), (6, 9), (2 , 3), (2, 8), (3, 7), (7, 8) y (5, 10). Por lo tanto, la cuenta es 9.
Entrada: N = 7, K = 3 
Salida:  
Explicación: Los posibles pares cuya suma es divisible por 3 son (1, 2), (1, 5), (2, 4), (2, 7), (3, 6), (4, 5) y (5, 7). Por lo tanto, la cuenta es 7. 
 

Enfoque simple: un enfoque ingenuo es usar un bucle anidado y verificar todos los pares posibles y su divisibilidad por K. La complejidad temporal de dicho enfoque es O (N ^ 2), que no es muy eficiente.
Enfoque eficiente : un enfoque eficiente es utilizar la técnica Hashing básica.
En primer lugar , cree la array rem[K], donde rem[i] contiene el recuento de números enteros de 1 a N, lo que da el resto i cuando se divide por K. rem[i] se puede calcular mediante la fórmula rem[i] = (N – i)/K + 1.
En segundo lugar , la suma de dos números enteros es divisible por K si: 
 

  • Ambos números enteros son divisibles por K. El recuento de los cuales se calcula mediante rem[0]*(rem[0]-1)/2.
  • El resto del primer entero es R y el resto del otro número es KR. Cuya cuenta se calcula mediante rem[R]*rem[KR], donde R varía de 1 a K/2.
  • K es par y ambos residuos son K/2. Cuya cuenta se calcula mediante rem[K/2]*(rem[K/2]-1)/2.

La suma de los conteos de todos estos casos da el conteo requerido de pares tal que su suma sea divisible por K. 
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to  find  the number of pairs
// from the set of natural numbers up to
// N whose sum is divisible by K
int findPairCount(int N, int K)
{
    int count = 0;
 
    // Declaring a Hash to store count
    int rem[K];
 
    rem[0] = N / K;
 
    // Storing the count of integers with
    // a specific remainder in Hash array
    for (int i = 1; i < K; i++)
        rem[i] = (N - i) / K + 1;
 
    // Check if K is even
    if (K % 2 == 0) {
        // Count of pairs when both
        // integers are divisible by K
        count += (rem[0] * (rem[0] - 1)) / 2;
 
        // Count of pairs when one remainder
        // is R and other remainder is K - R
        for (int i = 1; i < K / 2; i++)
            count += rem[i] * rem[K - i];
 
        // Count of pairs when both the
        // remainders are K / 2
        count += (rem[K / 2] * (rem[K / 2] - 1)) / 2;
    }
    else {
        // Count of pairs when both
        // integers are divisible by K
        count += (rem[0] * (rem[0] - 1)) / 2;
 
        // Count of pairs when one remainder is R
        // and other remainder is K - R
        for (int i = 1; i <= K / 2; i++)
            count += rem[i] * rem[K - i];
    }
 
    return count;
}
 
// Driver code
int main()
{
    int N = 10, K = 4;
 
    // Print the count of pairs
    cout << findPairCount(N, K);
 
    return 0;
}

Java

// Java implementation of the approach
class GfG
{
 
// Function to find the number of pairs
// from the set of natural numbers up to
// N whose sum is divisible by K
static int findPairCount(int N, int K)
{
    int count = 0;
 
    // Declaring a Hash to store count
    int rem[] = new int[K];
 
    rem[0] = N / K;
 
    // Storing the count of integers with
    // a specific remainder in Hash array
    for (int i = 1; i < K; i++)
        rem[i] = (N - i) / K + 1;
 
    // Check if K is even
    if (K % 2 == 0)
    {
        // Count of pairs when both
        // integers are divisible by K
        count += (rem[0] * (rem[0] - 1)) / 2;
 
        // Count of pairs when one remainder
        // is R and other remainder is K - R
        for (int i = 1; i < K / 2; i++)
            count += rem[i] * rem[K - i];
 
        // Count of pairs when both the
        // remainders are K / 2
        count += (rem[K / 2] * (rem[K / 2] - 1)) / 2;
    }
    else
    {
        // Count of pairs when both
        // integers are divisible by K
        count += (rem[0] * (rem[0] - 1)) / 2;
 
        // Count of pairs when one remainder is R
        // and other remainder is K - R
        for (int i = 1; i <= K / 2; i++)
            count += rem[i] * rem[K - i];
    }
 
    return count;
}
 
// Driver code
public static void main(String[] args)
{
    int N = 10, K = 4;
 
    // Print the count of pairs
    System.out.println(findPairCount(N, K));
}
}
 
// This code is contributed by Prerna Saini

Python3

# Python3 implementation of the approach
 
# Function to find the number of pairs
# from the set of natural numbers up to
# N whose sum is divisible by K
def findPairCount(N, K) :
    count = 0;
     
    # Declaring a Hash to store count
    rem = [0] * K;
     
    rem[0] = N // K;
     
    # Storing the count of integers with
    # a specific remainder in Hash array
    for i in range(1, K) :
        rem[i] = (N - i) // K + 1;
         
    # Check if K is even
    if (K % 2 == 0) :
         
        # Count of pairs when both
        # integers are divisible by K
        count += (rem[0] * (rem[0] - 1)) // 2;
         
        # Count of pairs when one remainder
        # is R and other remainder is K - R
        for i in range(1, K // 2) :
            count += rem[i] * rem[K - i];
         
        # Count of pairs when both the
        # remainders are K / 2
        count += (rem[K // 2] * (rem[K // 2] - 1)) // 2;
         
    else :
         
        # Count of pairs when both
        # integers are divisible by K
        count += (rem[0] * (rem[0] - 1)) // 2;
         
        # Count of pairs when one remainder is R
        # and other remainder is K - R
        for i in rage(1, K//2 + 1) :
            count += rem[i] * rem[K - i];
     
    return count;
 
# Driver code
if __name__ == "__main__" :
 
    N = 10 ; K = 4;
 
    # Print the count of pairs
    print(findPairCount(N, K));
 
# This code is contributed by Ryuga

C#

// C# implementation of the approach
class GfG
{
 
// Function to find the number of pairs
// from the set of natural numbers up to
// N whose sum is divisible by K
static int findPairCount(int N, int K)
{
    int count = 0;
 
    // Declaring a Hash to store count
    int[] rem = new int[K];
 
    rem[0] = N / K;
 
    // Storing the count of integers with
    // a specific remainder in Hash array
    for (int i = 1; i < K; i++)
        rem[i] = (N - i) / K + 1;
 
    // Check if K is even
    if (K % 2 == 0)
    {
        // Count of pairs when both
        // integers are divisible by K
        count += (rem[0] * (rem[0] - 1)) / 2;
 
        // Count of pairs when one remainder
        // is R and other remainder is K - R
        for (int i = 1; i < K / 2; i++)
            count += rem[i] * rem[K - i];
 
        // Count of pairs when both the
        // remainders are K / 2
        count += (rem[K / 2] * (rem[K / 2] - 1)) / 2;
    }
    else
    {
        // Count of pairs when both
        // integers are divisible by K
        count += (rem[0] * (rem[0] - 1)) / 2;
 
        // Count of pairs when one remainder is R
        // and other remainder is K - R
        for (int i = 1; i <= K / 2; i++)
            count += rem[i] * rem[K - i];
    }
 
    return count;
}
 
// Driver code
static void Main()
{
    int N = 10, K = 4;
 
    // Print the count of pairs
    System.Console.WriteLine(findPairCount(N, K));
}
}
 
// This code is contributed by mits

PHP

<?php
// PHP implementation of the approach
 
// Function to find the number of pairs
// from the set of natural numbers up
// to N whose sum is divisible by K
function findPairCount($N, $K)
{
    $count = 0;
 
    // Declaring a Hash to store count
    $rem = array(0, $K, NULL);
 
    $rem[0] = intval($N / $K);
 
    // Storing the count of integers with
    // a specific remainder in Hash array
    for ($i = 1; $i < $K; $i++)
        $rem[$i] = intval(($N - $i) / $K ) + 1;
 
    // Check if K is even
    if ($K % 2 == 0)
    {
        // Count of pairs when both
        // integers are divisible by K
        $count += ($rem[0] * intval(($rem[0] - 1)) / 2);
 
        // Count of pairs when one remainder
        // is R and other remainder is K - R
        for ($i = 1; $i < intval($K / 2); $i++)
            $count += $rem[$i] * $rem[$K - $i];
 
        // Count of pairs when both the
        // remainders are K / 2
        $count += ($rem[intval($K / 2)] *
                        intval(($rem[intval($K / 2)] - 1)) / 2);
    }
    else
    {
         
        // Count of pairs when both
        // integers are divisible by K
        $count += ($rem[0] * intval(($rem[0] - 1)) / 2);
 
        // Count of pairs when one remainder is R
        // and other remainder is K - R
        for ($i = 1; $i <= intval($K / 2); $i++)
            $count += $rem[$i] * $rem[$K - $i];
    }
 
    return $count;
}
 
// Driver code
$N = 10;
$K = 4;
 
// Print the count of pairs
echo findPairCount($N, $K);
 
// This code is contributed by ita_c
?>

Javascript

<script>
// javascript implementation of the approach
 
// Function to find the number of pairs
// from the set of natural numbers up to
// N whose sum is divisible by K
function findPairCount(N , K)
{
    var count = 0;
 
    // Declaring a Hash to store count
    var rem = Array.from({length: K}, (_, i) => 0);
 
    rem[0] = parseInt(N / K);
 
    // Storing the count of integers with
    // a specific remainder in Hash array
    for (i = 1; i < K; i++)
        rem[i] = parseInt((N - i) / K + 1);
 
    // Check if K is even
    if (K % 2 == 0)
    {
     
        // Count of pairs when both
        // integers are divisible by K
        count += parseInt((rem[0] * (rem[0] - 1)) / 2);
 
        // Count of pairs when one remainder
        // is R and other remainder is K - R
        for (i = 1; i < K / 2; i++)
            count += rem[i] * rem[K - i];
 
        // Count of pairs when both the
        // remainders are K / 2
        count += (rem[K / 2] * (rem[K / 2] - 1)) / 2;
    }
    else
    {
     
        // Count of pairs when both
        // integers are divisible by K
        count += (rem[0] * (rem[0] - 1)) / 2;
 
        // Count of pairs when one remainder is R
        // and other remainder is K - R
        for (i = 1; i <= K / 2; i++)
            count += rem[i] * rem[K - i];
    }
    return count;
}
 
// Driver code
var N = 10, K = 4;
 
// Print the count of pairs
document.write(findPairCount(N, K));
 
// This code is contributed by Princi Singh
</script>
Producción: 

10

 

Complejidad del Tiempo : O(K).

Espacio Auxiliar: O(K)
 

Publicación traducida automáticamente

Artículo escrito por rupesh_rao y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *