HiveBrain v1.2.0
Get Started
← Back to all entries
patterncModerate

Super calculator in C

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
supercalculatorstackoverflow

Problem

For my mathematical research, I am to deal with very large numbers and I know that the standard C types are not going to stand a chance against them due to their limited capacity, so I decided to write a super calculator in C language in hope that I won't have to resort to a super computer.

I started with an add function that I want to be reviewed for bugs if any, and possible improvement in performance and general programming aspects. Note that, on my system, the program was able to add a number consisting of 200 million digits of 9 to the same number in 0.98 seconds, which is pretty impressive, but still, if there is anything in performance that can be enhanced, let me know. That is because the multiplication function is going to be dependent on this function, and things will get slower because multiplication is repeated addition.

```
#include
#include
#include
#include

char add(char x, char *y);

int main(void)
{
clock_t t1 = clock();
/ ............................................................................................................................. /
size_t nd = 200 1000 1000; // 2 hundred million digits
char x = (char )malloc(nd + 1);
char y = (char )malloc(nd + 1);
if (!x || !y) {
fputs("error: memory allocation failed.\n", stderr);
goto dismantle;
}
/ assign x and y /
for (size_t i = 0; i = ylen);
size_t n = 0;
/ pointers to x and y /
char p1, p2;
char t1, t2;
/ assign pointers according to the value of var /
if (var) {
p1 = x + xlen - 1; t1 = x;
p2 = y + ylen - 1; t2 = y;
z = (char *)malloc(xlen + 2);
}
else {
p1 = y + ylen - 1; t1 = y;
p2 = x + xlen - 1; t2 = x;
z = (char *)malloc(ylen + 2);
}
/ check for allocation failure /
if (!z) {
fputs("error: memory allocation failed.\n", stderr);
return NULL;
}
/ stage 1 /
while (p2 >= t2)
{

Solution

You are using textual strings to represent numbers. This is not ideal for the processor. It is better to store the numbers as arrays of 32 or 64-bit unsigned integers, depending on the type of CPU. The only issue of course is that you might have to convert from and to the textual representation for your input and output, but if you have to perform many operations on your numbers, this is a small cost to pay.

There are existing libraries that can handle very large numbers (usually called "bignums"). One of them is the GNU Multiple Precision Arithmetic library. You can use that one if you want, or look at its source code to see how they handle large numbers.

Context

StackExchange Code Review Q#153320, answer score: 13

Revisions (0)

No revisions yet.