-
Notifications
You must be signed in to change notification settings - Fork 0
/
simpleMultiple.c
72 lines (54 loc) · 1.1 KB
/
simpleMultiple.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<limits.h>
int simpleMultiple(const int a,const int b,int *c){
int ret = 0;
int i = 0,b_;
*c = 0;
if(b==0){
return ret;
}
if(INT_MAX-a<=a){
ret = -1;
}
if(b<0){
b_=b*-1;
}else{
b_=b;
}
while(1){
if(a<0){
*c+=a*-1;
}else{
*c+=a;
}
i++;
if(INT_MAX-*c<=a) ret = -1;
if(i>=b_){
break;
}
}
if((a<0||b<0)&&!(a<0&&b<0)){
*c*=-1;
}
return ret;
}
int main(){
int a = (random()-RAND_MAX/2)%10000;
int b = (random()-RAND_MAX/2)%10000;
int c,r,i;
srandom(time(NULL));
r = simpleMultiple(a,b,&c);
printf("%d * %d = %d\nr = %d\n",a,b,c,r);
for(i=0;i<10e6;i++){
a=(random()-RAND_MAX/2)%10000;
b=(random()-RAND_MAX/2)%10000;
r = simpleMultiple(a,b,&c);
if(r==0&&c!=a*b){
printf("mismatched.\n");
printf("a = %d, b = %d, c = %d, a*b = %d\n",a,b,c,a*b);
}
}
return 0;
}