I'm writing a code like this
int reverse(int x) {
long long res;
......
if(x>0&&res>INT_MAX||x<0&&res>INT_MAX+1){
return 0;
}
......
}
It shows overflow,but when I add conversion to this it complies
int reverse(int x) {
long long res;
......
if(x>0&&res>(unsigned long long)INT_MAX||x<0&&res>(unsigned long long)INT_MAX+1){
return 0;
}
......
}
Can somebody please explain to me what is the problem?
INT_MAX+1 is evaluated as an integer addition of two ints. Since the resultant is not with the range of values that can be represented as an int, you see the overflow.
(unsigned long long)INT_MAX+1 is evaluated as an integer addition of two unsigned long longs. Since both sides of the operator and the resultant are well within the range of values that can be represented as an unsigned long long, there is no overflow.
INT_MAX + 1
In this sub-expression, the type of both operands of + are int, so the type of the result is int, causing integer overflow.
However, if you cast one operand to unsigned long long:
(unsigned long long)INT_MAX + 1
The type of the result if unsigned long long, thus no overflow, simple like that.
What triggers the overflow is the expression
INT_MAX+1
Because INT_MAX is of type int (32 bit integer), INT_MAX+1 exceeds the maximum value of int.
Once you cast it to unsigned long long (64 bit integer),
(unsigned long long)INT_MAX
Is now well below the maximum value for its type, and
(unsigned long long)INT_MAX + 1
is valid
Related
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
class Solution {
public:
vector<int> addToArrayForm(vector<int>& A, int K) {
int i=A.size()-1;
vector<int> result={};
long long int no=0;
for(int x:A)
{
no=no+x*pow(10,i);
i--;
}
no=no+K;
if(no==0)
return {0};
while(no>0)
{
long long int r=no%10;
result.push_back(r);
no=no/10;
}
reverse(result.begin(),result.end());
return result;
}
};
I am getting this error with long long.
Line 9: Char 14: runtime error: 1e+19 is outside the range of representable values of type 'long long' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:18:14
Provided that long long is implemented by a signed 64-bit integer, 1e19 is indeed out of the positive range of that type. The maximum representable value of that type would be 9223372036854775807.
As to whether 1e19 is a possible value, it is because it depends on the size of the vector A that you pass as input. You may want to limit your algorithm to only accept A of up to a certain size by adding a check against std::numeric_limits<long long>::digits10.
maybe initialise std::vector<long long int> result will solve your problem. Because you defined it as an integer, but you pusing back long long variable.
or you can use static_cast<type> to convert types temprorary for ongoing alegorithm (cppref: static_cast)
disclaimer: I answered, because I can't comment (I don't have 50 rep)
I read that conversion from int to long long int is promotion and hence thought that there shouldn't be any issue as there is no loss of data, unlike the vice versa conversion.
But when I multiply two ints of large value and store it in long long int, it is showing me negative number.
Eg:
int a=1000000, b=1000000;
long long int c=a*b;
cout<<c;
The above code gives me a negative value. Can someone explain why?
a*b is still of type int. Once it's evaluated, the result is then converted to long long int. At that point it's too late to avoid overflow. Convert one of your values to long long int before preforming the multiplication. Try this :
#include <iostream>
int main()
{
int a = 1000000, b = 1000000;
long long int c = static_cast<long long int>(a)*b;
std::cout << c;
return 0;
};
The multiplication is happening as an int, which overflows, giving Undefined Behaviour (in this case overflow, which is very normal - your combination of compiler+settings may even guarantee it), and after that the result is being converted to long long.
I think you want to do the conversion on one of the arguments before multiplication, so that the multiplication is performed using long longs:
long long c = static_cast<long long>(a)*b;
In this way, b will be promoted to long long before the multiplication takes place, and the whole operation will be performed safely, and with the desired result.
Because multiplying two ints will result in another int that comes with all the overflow problems attached. This int is then (after the fact) promoted to a long long int which still means it's not what you want.
Promote at least one of the operands to have the other promoted and get the result you want.
There's no real need for a solution to this, I just want to know why.
Let's take two numbers:
#include <iostream>
using namespace std;
int main()
{
unsigned long long int a = 17446744073709551615;
signed long long int b = -30000000003;
signed int c;
c = a/b;
cout << "\n\n\n" << c << endl;
}
Now, lately the answer I've been getting is zero. The size of my long long is 8 bytes, so more than enough to take it with the unsigned label. The C variable should also be big enough to handle the answer. (It should be -581 558 136, according to Google). So...
Edit I'd like to point out that on my machine...
Using numeric_limits a falls well withing the maximum of 18446744073709551615 and b falls within the minimum limits of -9223372036854775808.
You have a number of implicit conversions happening, most of them unnecessary.
unsigned long long int a = 17446744073709551615;
An unsuffixed decimal integer literal is of type int, long int, or long long int; it's never of an unsigned type. That particular value almost certainly exceeds the maximum value of a long long int (263-1). Unless your compiler has a signed integer type wider than 64 bits, that makes your program ill-formed.
Add a ULL suffix to ensure that the literal is of the correct type:
unsigned long long int a = 17446744073709551615ULL;
The value happens to be between 263-1 and 264-1, so it fits in a 64-bit unsigned type but not in a 64-bit signed type.
(Actually just the U would suffice, but it doesn't hurt to be explicit.)
signed long long int b = -30000000003;
This shouldn't be a problem. 30000000003 is of some signed integer type; if your compiler supports long long, which is at least 64 bits wide, there's no overflow. Still, as long as you need a suffix on the value of a, it wouldn't hurt to be explicit:
signed long long int b = -30000000003LL;
Now we have:
signed int c;
c = a/b;
Dividing an unsigned long long by a signed long long causes the signed operand to be converted to unsigned long long. In this case, the value being converted is negative, so it's converted to a large positive value. Converting -30000000003 to unsigned long long yields 18446744043709551613. Dividing 17446744073709551615 by 18446744043709551613 yields zero.
Unless your compiler supports integers wider than 64 bits (most don't), you won't be able to directly divide 17446744073709551615 by -30000000003 and get a mathematically correct answer, since there's no integer type that can represent both values. All arithmetic operators (other than the shift operators) require operands of the same type, with implicit conversions applied as necessary.
In this particular case, you can divide 17446744073709551615ULL by 30000000003ULL and then account for the sign. (Check the language rules for division of negative integers.)
If you really need to do this in general, you can resort to floating-point (which means you'll probably lose some precision) or use some arbitrary width integer arithmetic package like GMP.
b is getting treated as an unsigned number which is larger than a. Hence you are getting the answer as 0.
Try using it as
c = abs(a) / abs (b)
if ((a < 0 && b > 0 ) || (a> 0 && b < 0))
return -c;
return c;
The question actually comes from this snippet
int a = -1;
unsigned int c=1;
long long b = c<<31;
printf("%d %lld %d\n",a,b,a>b);
I tested it on Linux gcc (GCC) 4.4.6 20110731 (Red Hat 4.4.6-3), the result is:
-1 2147483648 0
Actually I cannot understand the result. I my opinion, when you do a>b, a is converted to long long first, so a is 0000...01111...1(32 zeros + 32 ones), b is 000..01000...00 (32 zeros + one + 31 zeros), then a should be bigger than b.
Am I missing something of integer comparison in C++?
Before the comparison the value of a is converted to a long long which still has the value -1.
The result is correct. a is a signed int, so -1 is negative. b is a signed long long; it has a positive sign. Of course a negative number is not greater than a positive.
If you wanted (for some reason!) to show a as an unsigned long long, this would do it:
printf("%ull %lld %d\n",a,b,a>b);
If you wanted to force it into an unsigned long long:
unsigned long long a=ax;
And if you wanted to compare it to b, and thereby treat it as an unsigned long long w/o declaring it as such:
printf("%d %lld %d\n",a,b, a > (unsigned long long) b);
int left = std::numeric_limits<int>::min();
int right = -1;
//the code below instead of give one more than int_max gives: 18446744071562067968
unsigned long long result = left * right;
I've tried to look up UAC but even according to UAC rules this should produce correct output. Any ideas why the result is incorrect?
It's undefined behavior to multiply the minimum value of a signed 2's complement int by -1, because the result is outside the range of the type.
In this case your output is consistent with the result having been -2147483648, i.e. the overflow appears to have wrapped around. You cannot rely on wraparound for signed types, only unsigned types.
Assigning the result of a calculation to unsigned long long does not change what type the calculation is performed in. As soon as you do the multiplication, you lose. So, convert one of the operands to unsigned long long before multiplying.
Both operands are int, so arithmetic is performed within the int type; the result of the operation overflows the range of int, so the result is undefined.
To get the result you expect, cast one operand to long long first:
unsigned long long result = left * (long long) right;
This is still potentially undefined behaviour; it's safer to convert to unsigned arithmetic as early as possible (since unsigned arithmetic wraps and doesn't overflow):
unsigned long long result = left * (unsigned long long) right;
Note that the result you arrived at is 0xffffffff80000000; this indicates that the actual result of the operation was std::numeric_limits<int>::min() in the int type, which was then sign-extended and cast to unsigned long long.
Tha cause is that the multiplication is commited in terms of int.
Both arguments are int, so multiplications gives an int agein, and you were right, it gives int_max + 1 which is equivivalent to int_min=-2147483648. So it is actually -2147483648, but for unsigned long long it is equivivalent to 18446744071562067968, see hex codes:
int_min = 80000000
(unsigned long long) (int min) = ffffffff80000000