Contar par de enteros que tienen suma par

Dados dos números enteros N y M , la tarea es contar todos los posibles pares de números enteros (i, j) (1 ≤ i ≤ N, 1 ≤ j ≤ M) tales que i + j sea par.

Ejemplos:

Entrada: N = 6, M = 4 
Salida: 12 
Explicación: Los pares (1, 1), (1, 3), (2, 2), (2, 4), (3, 1), (3, 3 ), (4, 2), (4, 4), (5, 1), (5, 3), (6, 2), (6, 4) cumplen la condición requerida. Por lo tanto, la cuenta es 12.

Entrada: N = 2 y M = 8 
Salida:
 

Enfoque ingenuo: el enfoque más simple para resolver este problema es atravesar el rango [1, M] para cada número en ese rango, atravesar el rango [1, N] y generar todos los pares posibles. Para cada par posible, comprueba si su suma es un número par o no. Si se encuentra que es cierto, incremente el conteo. Finalmente, imprima el conteo obtenido.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program for the above approach
#include <iostream>
using namespace std;
 
// Function to count pairs with even sum
int countEvenPairs(int N, int M)
{
     
    // Stores the count of pairs
    // with even sum
    int count = 0;
 
    // Traverse the range 1 to N
    for(int i = 1; i <= N; i++)
    {
         
        // Traverse the range 1 to M
        for(int j = 1; j <= M; j++)
        {
             
            // Check if the sum of the
            // pair (i, j) is even or not
            if ((i + j) % 2 == 0)
            {
                 
                // Update count
                count++;
            }
        }
    }
 
    // Return the count
    return count;
}
 
// Driver Code
int main()
{
    int N = 4;
    int M = 6;
     
    cout << countEvenPairs(N, M) << endl;
     
    return 0;
}
 
// This code is contributed by akhilsaini

Java

// Java program for the above approach
import java.io.*;
 
class GFG {
 
    // Function to count pairs with even sum
    public static int countEvenPairs(
        int N, int M)
    {
 
        // Stores the count of pairs
        // with even sum
        int count = 0;
 
        // Traverse the range 1 to N
        for (int i = 1; i <= N; i++) {
 
            // Traverse the range 1 to M
            for (int j = 1; j <= M; j++) {
 
                // Check if the sum of the
                // pair (i, j) is even or not
                if ((i + j) % 2 == 0) {
 
                    // Update count
                    count++;
                }
            }
        }
 
        // Return the count
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 4;
        int M = 6;
        System.out.print(
            countEvenPairs(N, M));
    }
}

Python3

# Python3 program for the above approach
 
# Function to count pairs with even sum
def countEvenPairs(N, M):
     
    # Stores the count of pairs
    # with even sum
    count = 0
     
    # Traverse the range 1 to N
    for i in range(1, N + 1):
     
        # Traverse the range 1 to M
        for j in range(1, M + 1):
         
            # Check if the sum of the
            # pair (i, j) is even or not
            if ((i + j) % 2 == 0):
               
                # Update count
                count += 1
     
    # Return the count
    return count
 
# Driver Code
if __name__ == '__main__':
     
  N = 4
  M = 6
   
  print(countEvenPairs(N, M))
   
# This code is contributed by akhilsaini

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Function to count pairs with even sum
public static int countEvenPairs(int N, int M)
{
     
    // Stores the count of pairs
    // with even sum
    int count = 0;
 
    // Traverse the range 1 to N
    for(int i = 1; i <= N; i++)
    {
         
        // Traverse the range 1 to M
        for(int j = 1; j <= M; j++)
        {
             
            // Check if the sum of the
            // pair (i, j) is even or not
            if ((i + j) % 2 == 0)
            {
                 
                // Update count
                count++;
            }
        }
    }
     
    // Return the count
    return count;
}
 
// Driver Code
public static void Main()
{
    int N = 4;
    int M = 6;
     
    Console.WriteLine(
        countEvenPairs(N, M));
}
}
 
// This code is contributed by akhilsaini

Javascript

<script>
 
// Javascript program for the above approach
 
// Function to count pairs with even sum
function countEvenPairs(N, M)
{
     
    // Stores the count of pairs
    // with even sum
    var count = 0;
 
    // Traverse the range 1 to N
    for(var i = 1; i <= N; i++)
    {
         
        // Traverse the range 1 to M
        for(var j = 1; j <= M; j++)
        {
             
            // Check if the sum of the
            // pair (i, j) is even or not
            if ((i + j) % 2 == 0)
            {
                 
                // Update count
                count++;
            }
        }
    }
 
    // Return the count
    return count;
}
 
// Driver code
var N = 4;
var M = 6;
 
document.write(countEvenPairs(N, M));
 
// This code is contributed by Kirti
 
</script>
Producción: 

12

 

Complejidad de tiempo: O(N*M) 
Complejidad de espacio: O(1)

Enfoque eficiente: el enfoque anterior se puede optimizar en función de las siguientes observaciones: 

  • número par + número par = número par
  • número impar + número impar = número par

Siga los pasos a continuación para resolver el problema: 

  • Inicialice dos variables, digamos nEven y nOdd , para almacenar el recuento de enteros pares e impares hasta N .
  • Inicialice dos variables, digamos mEven y mOdd , para almacenar el recuento de enteros pares e impares hasta M .
  • Finalmente, cuente el número requerido de pares usando la fórmula:

cuenta = nPar * mPar + nOdd * mOdd

A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count even pairs
int countEvenPairs(int N, int M)
{
 
    // Stores count of pairs having even sum
    int count = 0;
 
    // Stores count of even numbers up to N
    int nEven = floor(N / 2);
 
    // Stores count of odd numbers up to N
    int nOdd = ceil(N / 2);
 
    // Stores count of even numbers up to M
    int mEven = floor(M / 2);
 
    // Stores count of odd numbers up to M
    int mOdd = ceil(M / 2);
    count = nEven * mEven + nOdd * mOdd;
 
    // Return the count
    return count;
}
 
// Driver Code
int main()
{
    int N = 4;
    int M = 6;
    cout << countEvenPairs(N, M);
    return 0;
}
 
// This code is contributed by Dharanendra L V

Java

// Java program for the above approach
import java.io.*;
 
class GFG {
 
    // Function to count even pairs
    public static int countEvenPairs(
        int N, int M)
    {
 
        // Stores count of pairs having even sum
        int count = 0;
 
        // Stores count of even numbers up to N
        int nEven = (int)Math.floor((double)N / 2);
 
        // Stores count of odd numbers up to N
        int nOdd = (int)Math.ceil((double)N / 2);
 
        // Stores count of even numbers up to M
        int mEven = (int)Math.floor((double)M / 2);
 
        // Stores count of odd numbers up to M
        int mOdd = (int)Math.ceil((double)M / 2);
 
        count = nEven * mEven + nOdd * mOdd;
 
        // Return the count
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 4;
        int M = 6;
        System.out.print(countEvenPairs(N, M));
    }
}

Python3

# Python3 program for the above approach
import math
 
# Function to count even pairs
def countEvenPairs(N, M):
   
    # Stores count of pairs having even sum
    count = 0;
 
    # Stores count of even numbers up to N
    nEven = int(math.floor(N / 2));
 
    # Stores count of odd numbers up to N
    nOdd = int(math.ceil(N / 2));
 
    # Stores count of even numbers up to M
    mEven = int(math.floor(M / 2));
 
    # Stores count of odd numbers up to M
    mOdd = int(math.ceil(M / 2));
 
    count = nEven * mEven + nOdd * mOdd;
 
    # Return the count
    return count;
 
# Driver Code
if __name__ == '__main__':
    N = 4;
    M = 6;
    print(countEvenPairs(N, M));
 
# This code is contributed by 29AjayKumar

C#

// C# program for the above approach
using System;
 
class GFG
{
 
  // Function to count even pairs
  public static int countEvenPairs(int N, int M)
  {
 
    // Stores count of pairs having even sum
    int count = 0;
 
    // Stores count of even numbers up to N
    int nEven = (int)Math.Floor((double)N / 2);
 
    // Stores count of odd numbers up to N
    int nOdd = (int)Math.Ceiling((double)N / 2);
 
    // Stores count of even numbers up to M
    int mEven = (int)Math.Floor((double)M / 2);
 
    // Stores count of odd numbers up to M
    int mOdd = (int)Math.Ceiling((double)M / 2);
    count = nEven * mEven + nOdd * mOdd;
 
    // Return the count
    return count;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int N = 4;
    int M = 6;
    Console.Write(countEvenPairs(N, M));
  }
}
 
// This code is contributed by shikhasingrajput

Javascript

<script>
 
// Javascript program for the above approach
 
// Function to count even pairs
function countEvenPairs(N, M)
{
     
    // Stores count of pairs having even sum
    let count = 0;
 
    // Stores count of even numbers up to N
    nEven = parseInt(Math.floor(N / 2));
 
    // Stores count of odd numbers up to N
    nOdd = parseInt(Math.ceil(N / 2));
 
    // Stores count of even numbers up to M
    mEven = parseInt(Math.floor(M / 2));
 
    // Stores count of odd numbers up to M
    mOdd = parseInt(Math.ceil(M / 2));
 
    count = nEven * mEven + nOdd * mOdd;
 
    // Return the count
    return count;
}
 
// Driver Code
let N = 4;
let M = 6;
 
document.write(countEvenPairs(N, M));
 
// This code is contributed by mohan1240760
 
</script>
Producción: 

12

 

Tiempo Complejidad: O(1) 
Espacio Auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por avaies 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 *