Skip to content
Advertisement

How to compare signs of two numbers without using ?

I need to compare 2 numbers, if they have the same sign (positive or negative), print “same sign”. If they have a different sign, print “different sign”

The catch is, I need to do it without the use of < or > (greater than or less than) and only using addition and subtraction of num1 and num2. You can also use 0 (no other numbers).

Here is what it looks like with the <>s:

num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))

if num1 < 0 and num2 < 0:   print("same sign")

if num1 > 0 and num2 > 0:   print("same sign")

if num1 > 0 and num2 < 0:   print("different sign")

if num1 < 0 and num2 > 0:   print("different sign")

Advertisement

Answer

You can use subtract the number by itself and if the result equal to zero in the two numbers or non equal to zero is the two numbers then it is the same sign, else different sign, here is the code:

num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))

if num1 + 0 - num1 == 0 and num2 + 0 - num2 == 0:  print("same sign") # +

elif num1 + 0 - num1 != 0 and num2 + 0 - num2 != 0:  print("same sign") # -

else: print("different sign")
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement