many small processor C implementations can directly check the result of a math operation for overflow/underflow.
Another way is to use a receiving field that is twice the length of the underlying int size I.E. for an int size of 2, use a result field of 4 bytes. (perhaps by a long long int) or transfer both numbers to double fields and multiply them then convert back to int (however, some precision in the result (I.E. the least significant digit) may be inaccurate.
Another way is to use an appropriate function from the math.h library.
Another way is to use long multiplication using arrays:
this was copied from http://www.cquestions.com/2010/08/multiplication-of-large-numbers-in-c.html
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#define MAX 10000
char * multiply(char [],char[]);
int main(){
char a[MAX];
char b[MAX];
char *c;
int la,lb;
int i;
printf("Enter the first number : ");
scanf("%s",a);
printf("Enter the second number : ");
scanf("%s",b);
printf("Multiplication of two numbers : ");
c = multiply(a,b);
printf("%s",c);
return 0;
}
char * multiply(char a[],char b[]){
static char mul[MAX];
char c[MAX];
char temp[MAX];
int la,lb;
int i,j,k=0,x=0,y;
long int r=0;
long sum = 0;
la=strlen(a)-1;
lb=strlen(b)-1;
for(i=0;i<=la;i++){
a[i] = a[i] - 48;
}
for(i=0;i<=lb;i++){
b[i] = b[i] - 48;
}
for(i=lb;i>=0;i--){
r=0;
for(j=la;j>=0;j--){
temp[k++] = (b[i]*a[j] + r)%10;
r = (b[i]*a[j]+r)/10;
}
temp[k++] = r;
x++;
for(y = 0;y<x;y++){
temp[k++] = 0;
}
}
k=0;
r=0;
for(i=0;i<la+lb+2;i++){
sum =0;
y=0;
for(j=1;j<=lb+1;j++){
if(i <= la+j){
sum = sum + temp[y+i];
}
y += j + la + 1;
}
c[k++] = (sum+r) %10;
r = (sum+r)/10;
}
c[k] = r;
j=0;
for(i=k-1;i>=0;i--){
mul[j++]=c[i] + 48;
}
mul[j]='\0';
return mul;
}
Sample output of above code:
Enter the first number: 55555555
Enter the second number: 3333333333
Multiplication of two numbers:
185185183314814815
Logic for multiplication of large numbers
As we know in c there are not any such data types which can store a very large numbers. For example we want to solve the expression:
55555555 * 3333333333
Result of above expression is very big number which beyond the range of even long int or long double. Then question is how to store such a big numbers in c?
Solution is very simple i.e. using array. Above program has used same logic that is we are using as usual logic to multiply two numbers except instead of storing the data in the normal variables we are storing into the array.
m
for each pair (noting the actual places they represent, i.e. fours, twos, or ones)": Is there a straightforward way to do that? If (say) I'm working with 16-bit integers, and I have0x05F4
offset by one byte (i.e. effectively0x05F400
), how would compute the result of that mod0x6C31
? – Uredo