Why number is getting out of long long range in C++? - c++

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)

Related

C++ Data Type Range

I am trying to do a division of :-
#include <bits/stdc++.h>
using namespace std;
int main(){
int A = -2147483648;
int B = -1;
int C = A/B;
// this is not working
cout<<C<<endl;
// nor this is working
cout<<A/B<<endl;
// But this is working
cout<<-2147483648/-1<<endl; // printing the result 2147483648;
}
I am confused why this happening. Please explain.
Assuming the int type is 32-bits and uses two's complement representation, the first two cases exhibit undefined behavior because both -2147483648 and -1 fit in a int but 2147483648 does not.
In the third case, the expression -2147483648/-1 contains the integer literal 2147483648 (before being negated), and has the first type in which the value can fit. In this case, that would be long int. The rest of the calculation keeps the type, so no undefined behavior occurs.
You can change the data type to long long.
long long A = -2147483648;
long long B = -1;
long long C = A/B;
If your you need fractional result, try 'double' instead of 'long long'.

why am I getting long long maximum value as a return value?

I am trying to output -1 when the two strings are equal , but instead I get the unsigned long long maximum value as a return value , I tried casting -1 to long long and unsigned long long but it's not working , It worked when I used if-else condition and it also worked when I stored the return value of the expression in a variable , but why is it not working when I'm outputting the return value directly ?
#include<iostream>
int main(){
std::string a,b;
std::cin>>a>>b;
std::cout<<(a!=b?std::max(a.length(),b.length()):-1);
}
std::max(a.length(),b.length()) has an unsigned type (incapable of holding negative values). std::size_t. -1 will be converted to the same type and std::size_t(-1) becomes the largest value a std::size_t can hold.
To work around the problem, you can cast std::max(a.length(), b.length()) to a signed type, like std::intmax_t:
Example:
#include <cstdint>
std::cout<<(a != b ? static_cast<std::intmax_t>(std::max(a.length(), b.length())) : -1);

Why does implicit conversion of int to long long int give unexpected answer in C++?

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.

why overflow when compare long long with int

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

Why can't I divide a large number by a negative number C++

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;