You are given two integers A and B. Your task is to determine if the product of the integers A,A 1,A 2,...,B is positive, negative or zero.
Input The input contains two integers A and B (−109≤A≤B≤109).
Output If the product is positive, print Positive. If it is negative, print Negative. If it is zero, print Zero.
#include<iostream>
using namespace std;
int main ()
{
long long num1,num2;
bool check=false;
long long count=0;
cin>>num1>>num2;
while(num1<=num2)
{
if(num1==0)
{
check=true;
break;
}
if(num1<0)
{
count ;
num1 ;
}
else
{
num1 ;
}
}
if(count%2==0&&check==false)
{
cout<<"Positive";
}
else if(count%2!=0&&check==false)
{
cout<<"Negative";
}
else
cout<<"Zero";
return 0;
}
how can i get better algoritm which not take much time and without overflow if someone have better idea to check if the product is postive or negative or zero ?
CodePudding user response:
You probably remember from when you were little that the product of two positive numbers is positive.
You probably also remember that the product of two negative numbers is positive, and that the product of one negative and one positive number is negative.
In other words, multiplying by a positive number has no effect on the sign, and multiplying by a negative number turns into - and - into .
From this, you can deduce first of all that you can ignore the positive part of the range, as it has no effect on the result.
You can also deduce that the product of three negative numbers is the product of one positive number and one negative number, so it is negative.
You can further deduce that the product of four negative numbers is the product of two positive number, so it is positive.
Now you can discover a very simple pattern, and figure out how to solve this problem without multiplying any numbers at all - you only need to care about
- Is there a zero involved?
- How many negative numbers are there?
Working out the details left as an exercise.
(If your solution is more than a couple of lines long, you're on the wrong track.)
