Comprobar si el producto de números enteros de a a b es positivo, negativo o cero

Dados dos números enteros a y b , la tarea es comprobar si el producto de números enteros de la rabia v[a, b] es decir , a * (a + 1) * (a + 2) * … * b es positivo, negativo o cero . 
Ejemplos: 
 

Entrada: a = -10, b = -2 
Salida: Negativo
Entrada: a = -10, b = 2 
Salida: Cero 
 

Enfoque ingenuo: podemos ejecutar un ciclo de a a b y multiplicar todos los números que comienzan de a a b y verificar si el producto es positivo, negativo o cero. Esta solución fallará para valores grandes de a y b y dará como resultado un desbordamiento.
Enfoque eficiente: Hay tres casos posibles: 
 

  1. Si a > 0 yb > 0 , el producto resultante será positivo.
  2. Si a < 0 y b > 0 , el resultado será cero como a * (a + 1) * … * 0 * … (b – 1) * b = 0 .
  3. Si a < 0 y b < 0 , el resultado dependerá de la cantidad de números (ya que todos los números son negativos) 
    • Si el conteo de números negativos es par, el resultado será positivo.
    • De lo contrario, el resultado será negativo.

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

C++

// C++ implementation of the approach
#include <iostream>
using namespace std;
 
// Function to check whether the product
// of integers of the range [a, b]
// is positive, negative or zero
void solve(long long int a, long long int b)
{
 
    // If both a and b are positive then
    // the product will be positive
    if (a > 0 && b > 0) {
        cout << "Positive";
    }
 
    // If a is negative and b is positive then
    // the product will be zero
    else if (a <= 0 && b >= 0) {
        cout << "Zero" << endl;
    }
 
    // If both a and b are negative then
    // we have to find the count of integers
    // in the range
    else {
 
        // Total integers in the range
        long long int n = abs(a - b) + 1;
 
        // If n is even then the resultant
        // product is positive
        if (n % 2 == 0) {
            cout << "Positive" << endl;
        }
        // If n is odd then the resultant
        // product is negative
        else {
            cout << "Negative" << endl;
        }
    }
}
 
// Driver code
int main()
{
    int a = -10, b = -2;
 
    solve(a, b);
 
    return 0;
}

Java

// Java implementation of the approach
import java.io.*;
 
class GFG
{
 
// Function to check whether the product
// of integers of the range [a, b]
// is positive, negative or zero
static void solve(long a, long b)
{
 
    // If both a and b are positive then
    // the product will be positive
    if (a > 0 && b > 0)
    {
        System.out.println( "Positive");
    }
 
    // If a is negative and b is positive then
    // the product will be zero
    else if (a <= 0 && b >= 0)
    {
        System.out.println( "Zero" );
    }
 
    // If both a and b are negative then
    // we have to find the count of integers
    // in the range
    else
    {
 
        // Total integers in the range
        long n = Math.abs(a - b) + 1;
 
        // If n is even then the resultant
        // product is positive
        if (n % 2 == 0)
        {
            System.out.println( "Positive");
        }
         
        // If n is odd then the resultant
        // product is negative
        else
        {
            System.out.println( "Negative");
        }
    }
}
 
    // Driver code
    public static void main (String[] args)
    {
        int a = -10, b = -2;
     
        solve(a, b);
    }
}
 
// This code is contributed by anuj_67..

Python3

# Python 3 implementation of the approach
 
# Function to check whether the product
# of integers of the range [a, b]
# is positive, negative or zero
def solve(a,b):
     
    # If both a and b are positive then
    # the product will be positive
    if (a > 0 and b > 0):
        print("Positive")
 
    # If a is negative and b is positive then
    # the product will be zero
    elif (a <= 0 and b >= 0):
        print("Zero")
 
    # If both a and b are negative then
    # we have to find the count of integers
    # in the range
    else:
         
        # Total integers in the range
        n = abs(a - b) + 1
 
        # If n is even then the resultant
        # product is positive
        if (n % 2 == 0):
            print("Positive")
             
        # If n is odd then the resultant
        # product is negative
        else:
            print("Negative")
 
# Driver code
if __name__ == '__main__':
    a = -10
    b = -2
 
    solve(a, b)
     
# This code is contributed by
# Surendra_Gangwar

C#

// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to check whether the product
    // of integers of the range [a, b]
    // is positive, negative or zero
    static void solve(long a, long b)
    {
     
        // If both a and b are positive then
        // the product will be positive
        if (a > 0 && b > 0)
        {
            Console.WriteLine( "Positive");
        }
     
        // If a is negative and b is positive then
        // the product will be zero
        else if (a <= 0 && b >= 0)
        {
            Console.WriteLine( "Zero" );
        }
     
        // If both a and b are negative then
        // we have to find the count of integers
        // in the range
        else
        {
     
            // Total integers in the range
            long n = Math.Abs(a - b) + 1;
     
            // If n is even then the resultant
            // product is positive
            if (n % 2 == 0)
            {
                Console.WriteLine( "Positive");
            }
             
            // If n is odd then the resultant
            // product is negative
            else
            {
                Console.WriteLine( "Negative");
            }
        }
    }
     
    // Driver code
    public static void Main ()
    {
        int a = -10, b = -2;
     
        solve(a, b);
    }
}
 
// This code is contributed by AnkitRai01

Javascript

<script>
 
// Javascript  implementation of the approach
 
// Function to check whether the product
// of integers of the range [a, b]
// is positive, negative or zero
function  solve( a,  b)
{
 
    // If both a and b are positive then
    // the product will be positive
    if (a > 0 && b > 0)
    {
        document.write( "Positive");
    }
 
    // If a is negative and b is positive then
    // the product will be zero
    else if (a <= 0 && b >= 0)
    {
        document.write( "Zero" );
    }
 
    // If both a and b are negative then
    // we have to find the count of integers
    // in the range
    else
    {
 
        // Total integers in the range
        let  n = Math.abs(a - b) + 1;
 
        // If n is even then the resultant
        // product is positive
        if (n % 2 == 0)
        {
            document.write( "Positive");
        }
         
        // If n is odd then the resultant
        // product is negative
        else
        {
            document.write( "Negative");
        }
    }
}
 
    // Driver code
     
        let a = -10;
        let b = -2;
     
        solve(a, b);
 
 
// This code is contributed by Bobby
 
</script>
Producción: 

Negative

 

Complejidad de tiempo: O(1), ya que no hay bucle.
Espacio Auxiliar: O(1), ya que no se requiere espacio adicional.

Publicación traducida automáticamente

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