Skip to content

Instantly share code, notes, and snippets.

@hiepph
Last active September 29, 2015 14:05
Show Gist options
  • Save hiepph/43d1309b23163a2c92f7 to your computer and use it in GitHub Desktop.
Save hiepph/43d1309b23163a2c92f7 to your computer and use it in GitHub Desktop.
Calculate sum of very large numbers
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "stack_list.h"
/* Check if stacks holding numbers are all empty */
int AllEmpty(stack_t **stack, int n)
{
int i;
for(i = 0; i < n; i++) {
if(!Empty(stack[i])) {
return 0; // at least 1 not empty
}
}
return 1; // all empty
}
stack_t *add_large_num(stack_t **stack, int n)
{
stack_t *result = Initialize();
int save, sum, remainder = 0;
int i;
while(!(AllEmpty(stack, n) && remainder == 0)) {
/* Initialize sum of each individual line of num */
sum = 0;
/* Pop each stacks and add to sum */
for(i = 0; i < n; i++) {
if(!Empty(stack[i])) {
Pop(&stack[i], &save);
sum += save;
}
}
/* Add sum with previous remainder */
sum += remainder;
/* decide remainder + Fix sum to num */
remainder = sum / 10;
sum = sum - remainder * 10;
/* Push sum to result stack */
Push(&result, sum);
}
return result;
}
/* Display to screen also empty the list */
void Print(stack_t **top)
{
int save;
while(!Empty(*top)) {
Pop(top, &save);
printf("%d", save);
}
printf("\n");
}
int main(void)
{
int n, i;
char ch;
int num;
printf("* How many numbers to add: ");
scanf("%d", &n); getchar();
stack_t *stack[n];
/* input numbers */
for(i = 0; i < n; i++) {
printf("> Enter number %d: ", i + 1);
// initialize each stack
stack[i] = Initialize();
// then add the number in
while((ch = getchar()) != '\n') {
num = ch - '0'; // turn char to digit
Push(&stack[i], num);
}
}
/* add numbers and print result */
printf("\n* Sum = ");
stack_t *sum = add_large_num(stack, n);
Print(&sum);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "stack_list.h"
stack_t *Initialize()
{
stack_t *top = NULL;
return top;
}
int Empty(stack_t *top)
{
return top == NULL;
}
void Push(stack_t **top, data_t data)
{
// create new stack's node
stack_t *NewNode = (stack_t*)malloc(sizeof(stack_t));
assert(NewNode != NULL);
NewNode->data = data;
// push into stack and make new top
NewNode->next = *top;
*top = NewNode;
}
stack_t *Pop(stack_t **top, data_t *save)
{
if(Empty(*top)) {
printf("ERROR: Stack is empty. Can't pop.\n");
return NULL;
}
// save the data
*save = (**top).data;
stack_t *temp = *top;
*top = (**top).next;
free(temp);
return *top;
}
#ifndef STACK_LIST_H
#define STACK_LIST_H
typedef int data_t;
typedef struct StackNode {
data_t data;
struct StackNode *next;
} stack_t;
stack_t *Initialize();
int Empty(stack_t *top);
void Push(stack_t **top, data_t data);
stack_t *Pop(stack_t **top, data_t *save);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment