Check whether product of integers from a to b is positive, negative or zero in Python


Suppose we have lower limit and upper limit of a range [l, u]. We have to check whether the product of the numbers in that range is positive or negative or zero.

So, if the input is like l = -8 u = -2, then the output will be Negative, as the values in that range is [-8, -7, -6, -5, -4, -3, -2], then the product is -40320 so this is negative.

To solve this, we will follow these steps −

  • if l and u both are positive, then
    • return "Positive"
  • otherwise when l is negative and u is positive, then
    • return "Zero"
  • otherwise,
    • n := |l - u| + 1
    • if n is even, then
      • return "Positive"
    • return "Negative"

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def solve(l,u):
   if l > 0 and u > 0:
      return "Positive"
   elif l <= 0 and u >= 0:
      return "Zero"
   else: 
      n = abs(l - u) + 1
      if n % 2 == 0:
         return "Positive"
      return "Negative"
   
l = -8
u = -2
print(solve(l,u))

Input

-8, -2

Output

Negative

Updated on: 16-Jan-2021

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements