Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check whether product of integers from a to b is positive, negative or zero in Python
When we need to determine the sign of a product of integers in a range [a, b], we don't need to calculate the actual product. Instead, we can use mathematical rules to determine if the result will be positive, negative, or zero.
So, if the input is like a = -8, b = -2, then the output will be Negative, as the values in that range are [-8, -7, -6, -5, -4, -3, -2], and the product is -40320 which is negative.
Algorithm
To solve this efficiently, we follow these steps:
- If both a and b are positive, the product is always positive
- If a is negative and b is positive (range contains zero), the product is zero
- If both a and b are negative, count the negative numbers:
- If count is even, product is positive
- If count is odd, product is negative
Example
def check_product_sign(a, b):
if a > 0 and b > 0:
return "Positive"
elif a <= 0 and b >= 0:
return "Zero"
else:
# Both are negative
count = abs(a - b) + 1
if count % 2 == 0:
return "Positive"
return "Negative"
# Test case 1: Range with negative numbers
a = -8
b = -2
result = check_product_sign(a, b)
print(f"Range [{a}, {b}]: {result}")
# Test case 2: Range including zero
a = -3
b = 2
result = check_product_sign(a, b)
print(f"Range [{a}, {b}]: {result}")
# Test case 3: Range with positive numbers
a = 2
b = 5
result = check_product_sign(a, b)
print(f"Range [{a}, {b}]: {result}")
Range [-8, -2]: Negative Range [-3, 2]: Zero Range [2, 5]: Positive
How It Works
The algorithm works based on these mathematical principles:
- Positive numbers: Product of positive numbers is always positive
- Zero included: Any product containing zero equals zero
- Negative numbers: Product of even count of negatives is positive, odd count is negative
Alternative Implementation
def determine_product_sign(start, end):
# Check if range includes zero
if start <= 0 <= end:
return "Zero"
# All positive numbers
if start > 0:
return "Positive"
# All negative numbers
negative_count = end - start + 1
return "Positive" if negative_count % 2 == 0 else "Negative"
# Test the function
test_cases = [(-8, -2), (-3, 2), (2, 5), (-5, -1)]
for start, end in test_cases:
result = determine_product_sign(start, end)
print(f"Range [{start}, {end}]: {result}")
Range [-8, -2]: Negative Range [-3, 2]: Zero Range [2, 5]: Positive Range [-5, -1]: Positive
Conclusion
This approach efficiently determines the sign of a product without calculating the actual value. The key insight is using the mathematical rule that an even number of negative factors produces a positive result, while an odd number produces a negative result.
