Overflow
Write a program that reads an expression consisting of two non-negative integer and an operator. Determine if either integer or the result of the expression is too large to be represented as a “normal” signed integer (type integer if you are working Pascal, type int if you are working in C).
Input
An unspecified number of lines. Each line will contain an integer, one of the two operators + or *, and another integer.
Output
For each line of input, print the input followed by 0-3 lines containing as many of these three messages as are appropriate: “first number too big”, “second number too big”, “result too big”.
Sample Input
300 + 3
9999999999999999999999 + 11
Sample Output
300 + 3
9999999999999999999999 + 11
first number too big
result too big
C Code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define max 2147483647
long n1,n2;
char number_1[10000],number_2[10000],op[2];
frist_n(char a[])
{
int len,i;
long val=0;
len=strlen(a);
i=0;
while(a[i]=='0'&&i<len)
{
i++;
val++;
}
if(i==len&&a[i-1]=='0') { n1= 0; return 0; }
if((len-val)>10) { printf("first number too big\n"); n1=-1; return 0; }
else if(atof(a)>max) { printf("first number too big\n"); n1=-1; return 0; }
else n1=atof(a);
return 0;
}
scend_n(char b[])
{
int len,i,val=0;
len=strlen(b);
i=0;
while(b[i]=='0' && i<len)
{
i++;
val++;
}
if(i==len && b[i-1]=='0') { n2=0; return 0; }
if((len-val)>10) { printf("second number too big\n"); n2=-1; return 0;}
else if(atof(b)>max) { printf("second number too big\n"); n2=-1; return 0;}
else n2=atof(b);
return 0;
}
result(char b[],char a[],char op[])
{
long i,k;
if(!n2||!n1) return 0;
else if(n1==-1||n2==-1) printf("result too big\n");
else
{
if(op[0]=='+')
if(atof(a)+atof(b)>max) printf("result too big\n");
if(op[0]=='*')
if(atof(a)*atof(b)>max) printf("result too big\n");
}
return 0;
}
main()
{
while(scanf("%s %s %s",number_1,op,number_2)==3)
{
n1=1;n2=2;
printf("%s %s %s\n",number_1,op,number_2);
frist_n(number_1);
scend_n(number_2);
result(number_1,number_2,op);
}
return 0;
}