How to deal with overflow in C

I am new to programming, and today I was just playing around coding trying to use functions, and I made a simple piece of code that worked on the math problem that I had in one of my classes. he basically takes the formula (number of bacteria) * 2 ^ hours and calculates this.

My problem is that when I get a really large amount, it does not return correctly, I always get -2147483648 back after a certain size of the number. I guess this has something to do with overflow, but I'm not 100% sure how this works. I am trying to figure out how to get the actual numbers I'm looking for after I hit this overflow. So what can I do to deal with overflow?

At first I just set everything to int, but after some reading I thought that maybe everything will change until a long time, it can help me, but it’s not so, if it is terrible for me, and I will let you know! In addition, the number of tests I use is 1500 and 24, which always returns a higher number.

Here is the code Thank you!

#include<stdio.h> #include<math.h> long bacteria(long b, long h); int main(void) { long f,g; scanf("%ld%ld",&f,&g); f = bacteria(f,g); printf("%ld\n",f); return 0; } long bacteria(long b,long h) { long d; printf("%ld %ld\n",b,h); d = b * (pow(2,h)); return d; } 
+5
source share
3 answers

Yes, your suspect is overflowing rights. C data type has some range. You need to use some bignum library to handle cases where you need a wider range. Also note that pow returns double, not long , as you might expect.

If you don't need precision, you can use double instead of long , which caters to a much wider range.

Real time example here

+2
source

Good question. I ran into the same problem a while ago using the example below. Check it out if it helps you.

http://discuss.codechef.com/questions/7349/computing-factorials-of-a-huge-number-in-cc-a-tutorial

The code below is from the link above.

 #include<stdio.h> int main() { int t; int a[200]; //array will have the capacity to store 200 digits. int n,i,j,temp,m,x; scanf("%d",&t); while(t--) { scanf("%d",&n); a[0]=1; //initializes array with only 1 digit, the digit 1. m=1; // initializes digit counter temp = 0; //Initializes carry variable to 0. for(i=1;i<=n;i++) { for(j=0;j<m;j++) { x = a[j]*i+temp; //x contains the digit by digit product a[j]=x%10; //Contains the digit to store in position j temp = x/10; //Contains the carry value that will be stored on later indexes } while(temp>0) //while loop that will store the carry value on array. { a[m]=temp%10; temp = temp/10; m++; // increments digit counter } } for(i=m-1;i>=0;i--) //printing answer printf("%d",a[i]); printf("\n"); } return 0; } 
+2
source

use longlong datatype instead of simple long to store large values.

+1
source

Source: https://habr.com/ru/post/1204299/


All Articles