Reputation: 754
Posted the whole code(if needed)
/* multiplication of n1 and n2*/
#include<stdio.h>
int arr[200]; //for storing the binary representation of n2
int k=0; // to keep the count of the no of digits in the binary representation
void bin(int n)
{
if(n>1)
bin(n/2);
arr[k++]=n%2;
}
int main()
{
int n1=1500000;
int n2=10000000;
int i=0,t=0;
long long int temp,pro=0;
bin(n2); // calculating the binary of n2 and stroring in 'arr'
for(i=k-1; i>=0 ;i--)
{
temp = (n1*arr[i]) << t; /* Why need cast here ? */
pro = pro + temp;
t++;
}
printf("product: %lld",pro);
return 0;
}
In the above program, I am not getting the desired output. But when I do this:
temp = (n1*(long long int)arr[i]) << t;
,
then I am getting the correct output !
I am not able to understand the above behavior ?
Upvotes: 0
Views: 119
Reputation: 1434
a multiplication between two integer goes into an integer unless you cast one of them to something else. So in the first multiplication the result is stored into an integer (32 bit signed on a 32 bit system), in the second case into a long long (64 bit unsigned on a 32 bit system). You may prefer using types like int64_t
to have better portability.
You can use sizeof(int)
, sizeof(long long)
to see the difference between the two.
Upvotes: 2
Reputation: 9819
n1, as well as arr[i], are integers. Without the cast, you get an integer multiplication (which may overflow), shift that integer left (again producing an integer result that may overflow), then assign that integer to temp.
If you cast arr[i] to long long, all calculations are done in long. So, if your integers are 32 bit (and thus limited to about 2e10), your integers will overflow, but the long longs, which should be 64 bit, will not.
Upvotes: 2
Reputation: 1942
I suspect that an int
isn't large enough to store the result of (n1*arr[i])
, so casting to a (long long int)
gives enough room to store the result.
int
Not smaller than short. At least 16 bits.
long long int
Not smaller than long. At least 64 bits.
Have a look at C++ Data Types.
Upvotes: 2
Reputation: 16043
It seems likely that on your system int
is 32 bits and long long int
is 64 bits.
n1
and arr[i]
are both int
, and result of multiplication is then int
. But there is not enough bits in int
to hold the answer because it is too big.
When you cast one member of the operation to long long int
, then result will also be long long int
too.
Upvotes: 3