Skip to content

Instantly share code, notes, and snippets.

@rkotov93
Created June 4, 2011 17:43
Show Gist options
  • Save rkotov93/1008117 to your computer and use it in GitHub Desktop.
Save rkotov93/1008117 to your computer and use it in GitHub Desktop.
Long Math
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NMAX 1002
void invert(int*); // Инвертирует число
void sum(int*, int*); // Суммирует два числа
int max(int, int); // Возвращает максимальное число
int* divide (int*, int);
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int* nums[NMAX];
int* general;
int* average;
int* result;
int i = 0, j = 1, m = 0;
int x;
char c;
for (m = 0; m < NMAX; m++) nums[m] = (int*)malloc(NMAX*sizeof(int));
general = (int*)malloc(NMAX*sizeof(int));
average = (int*)malloc(NMAX*sizeof(int));
result = (int*)malloc(NMAX*sizeof(int));
while (scanf("%c", &c) > 0) {
if (c >= '0' && c <= '9') {
nums[i][j] = c - '0';
j++;
} else
if (j > 1) {
nums[i][0] = j-1;
i++;
j = 1;
}
}
if (j > 1) {
nums[i][0] = j-1;
i++;
}
//printf("%d\n", i);
for (x = 0; x < NMAX+1; x++) general[x] = 0;
for (x = 0; x < i; x++) {
invert(nums[x]);
sum(general, nums[x]);
}
//for (j = 1; j <= general[0]; j++) printf("%d", general[j]);
//printf("\n");
result = divide(general, i);
invert(result);
for (i = 1; i <= result[0]; i++) printf("%d", result[i]);
return 0;
}
void invert(int* mass) {
int x;
int i;
for (i = 1; i <= mass[0]/2; i++) {
x = mass[i];
mass[i] = mass[mass[0]-(i-1)];
mass[mass[0]-(i-1)] = x;
}
}
void sum(int* to, int* from) {
int i, j = 0;
to[0] = max(to[0], from[0]);
for (i = 1; i <= max(to[0], from[0]); i++) {
to[i] = to[i] + from[i];
if (to[i] >= 10) {
to[i] = to[i]-10;
to[i+1] = to[i+1] + 1;
if (i + 1 > to[0]) j++;
}
}
to[0] += j;
}
int max(int x1, int x2) {
return x1 >= x2 ? x1 : x2;
}
int* divide(int* a, int b) {
int r = 0;
int i;
int* result;
result = (int*)malloc(a[0]*sizeof(int));
for(i = a[0]; i >= 1; i--) {
r = r * 10 + a[i];
result[i] = r / b;
r %= b;
}
result[0] = a[0];
while (result[0] > 1 && result[result[0]] == 0) --result[0];
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment