Created
October 5, 2011 08:47
-
-
Save vaclavbohac/1263954 to your computer and use it in GitHub Desktop.
Super long sums
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Solution to the UVa Online Judge problem no. 10013 */ | |
#include <stdlib.h> | |
#include <stdio.h> | |
#define MAX_SIZE 1000000 | |
char buffer[4 * MAX_SIZE], | |
number[MAX_SIZE]; | |
int main() { | |
int n, m, i, j, tmp, carry; | |
if (scanf("%d", &n) != 1) { | |
return 0; | |
} | |
number[0] = '1'; | |
for (i = 0; i < n; i++) { | |
if (scanf("%d\n", &m) != 1) { | |
return 0; | |
} | |
buffer[0] = 0; | |
if (fread(buffer, 1, m * 4, stdin) == -1) { | |
return 0; | |
} | |
buffer[m * 4] = 0; | |
for (number[m + 2] = carry = 0, j = 1; j <= m; j++) { | |
tmp = buffer[4*(m-j)] + buffer[4*(m-j)+2] - 48 + carry; | |
carry = tmp > 57; | |
number[m - j + 1] = carry ? tmp - 10 : tmp; | |
} | |
number[m + 1] = '\n'; | |
if (fwrite(number + 1 - carry, 1, m + 1 + carry, stdout) == 0) { | |
return 0; | |
} | |
if (i < (n - 1)) { | |
printf("\n"); | |
} | |
} | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
def line_nums | |
begin | |
l = gets.strip! | |
end while l.empty? | |
l.to_i | |
end | |
def add_numbers(lines) | |
buffer = STDIN.read lines * 4 | |
number = [] | |
carry = false | |
(lines - 1).downto 0 do |i| | |
a = buffer[4 * i].chr.to_i | |
b = buffer[4 * i + 2].chr.to_i | |
c = a + b | |
c += 1 if carry | |
number[i] = c % 10 | |
carry = c > 9 | |
end | |
if carry | |
number.unshift 1 | |
end | |
number | |
end | |
def print_number(number) | |
puts number.join('') | |
end | |
if __FILE__ == $0 | |
n = gets | |
n.to_i.times do |i| | |
print_number add_numbers line_nums | |
puts if i < n.to_i - 1 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment