-
Notifications
You must be signed in to change notification settings - Fork 0
/
101-mul.c
132 lines (111 loc) · 1.92 KB
/
101-mul.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include "main.h"
/**
* _memset - fills memory with a constant byte
*
* @s: input pointer
* @b: characters
* @n: bytes
*
* Return: pointer
*/
char *_memset(char *s, char b, unsigned int n)
{
unsigned int a = 0;
while (a < n)
{
s[a] = b;
a++;
}
return (s);
}
/**
* _calloc - function that allocates memory
* for an array using memset
*
* @nmemb: array
* @size: each element
*
* Return: pointer
*/
void *_calloc(unsigned int nmemb, unsigned int size)
{
char *ptr;
if (nmemb == 0 || size == 0)
return (NULL);
ptr = malloc(nmemb * size);
if (ptr == NULL)
return (NULL);
_memset(ptr, 0, nmemb * size);
return (ptr);
}
/**
* multiply - initialize array with 0 byte
*
* @s1: first string
* @s2: second string
*
* Return: nothing
*/
void multiply(char *s1, char *s2)
{
int i, l1, l2, total_l, f_digit, s_digit, res = 0, tmp;
char *ptr;
void *temp;
l1 = _length(s1);
l2 = _length(s2);
tmp = l2;
total_l = l1 + l2;
ptr = _calloc(sizeof(int), total_l);
/* store our pointer address to free later */
temp = ptr;
for (l1--; l1 >= 0; l1--)
{
f_digit = s1[l1] - '0';
res = 0;
l2 = tmp;
for (l2--; l2 >= 0; l2--)
{
s_digit = s2[l2] - '0';
res += ptr[l2 + l1 + 1] + (f_digit * s_digit);
ptr[l1 + l2 + 1] = res % 10;
res /= 10;
}
if (res)
ptr[l1 + l2 + 1] = res % 10;
}
while (*ptr == 0)
{
ptr++;
total_l--;
}
for (i = 0; i < total_l; i++)
printf("%i", ptr[i]);
printf("\n");
free(temp);
}
/**
* main - Entry point
*
* Description: a program that multiplies
* two positive numbers
*
* @argc: number of arguments
* @argv: arguments array
*
* Return: 0 on success 98 on faliure
*/
int main(int argc, char *argv[])
{
char *n1 = argv[1];
char *n2 = argv[2];
if (argc != 3 || check_number(n1) || check_number(n2))
error_exit();
if (*n1 == '0' || *n2 == '0')
{
_putchar('0');
_putchar('\n');
}
else
multiply(n1, n2);
return (0);
}