Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the error in multiplication of long long Integer?

 #include<stdio.h>
 int main()
 {
     long long int t=8*9*100000000;// 8 zeros
     printf("%lld\n",t);
     return 0;
 }

gives result: -1389934592


please reply

 #include<stdio.h>
 int main()
 {
     long long int t=8*9*1000000000; //9zeros
     printf("%lld\n",t);
     return 0;
 }

gives result: -1014444032


while all other multiplication gave correct result i.e.

 #include<stdio.h>
 int main()
 {
     long long int t=8*9*10000000000; //10zeros or greater or zeros <=6
     printf("%lld\n",t);
     return 0;
 }

gives result: 720000000000


like image 542
Shivam Chauhan Avatar asked Dec 14 '22 14:12

Shivam Chauhan


1 Answers

100000000 with 8 zeros or 1000000000 with 9 zeros fit into an 32bit int (long, not long long), and that´s the default. Then the multiplications are made with 32bit int´s,
and then the result gets converted to 64bit.
This is a problem because the result won´t fit into 32bit => Overflow.

With the with 10 zeros, you´ll have an 64bit int from the start,
because this number won´t fit into an 32bit int.
=> Calculations are done with 64bit, no problem.

If you want the 8-zero and 9-zero number to be used as long long, use LL, ie. 100000000LL

like image 92
deviantfan Avatar answered Jan 12 '23 20:01

deviantfan