Created
March 18, 2012 08:15
-
-
Save edma2/2069891 to your computer and use it in GitHub Desktop.
Project Euler #13
This file contains 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
/* | |
* Project Euler #13 | |
* Eugene Ma | |
* | |
* Real Answer: 5537376230 | |
*/ | |
#include <stdio.h> | |
#include <string.h> | |
#define LINES 100 | |
#define DIGITS 50 | |
char numbers[LINES][DIGITS]; | |
int sum_digits(int n); | |
int main(void) { | |
FILE *fp; | |
int i, j; | |
int sum; | |
int carry = 0; | |
int digits[10]; | |
fp = fopen("input.txt", "r"); | |
if (fp == NULL) { | |
perror("fopen"); | |
return -1; | |
} | |
for (i = 0; i < LINES; i++) { | |
char buf[52]; /* '\n', '\0' */ | |
if (fgets(buf, sizeof(buf), fp) == NULL) { | |
fclose(fp); | |
perror("fgets"); | |
return -1; | |
} | |
strncpy(numbers[i], buf, DIGITS); | |
for (j = 0; j < DIGITS; j++) | |
numbers[i][j] -= '0'; | |
} | |
fclose(fp); | |
for (i = DIGITS-1; i >= 0; i--) { | |
sum = sum_digits(i) + carry; | |
carry = sum/10; | |
digits[i%10] = sum % 10; | |
} | |
/* The first few digits are carry digits */ | |
printf("%d", carry); | |
/* Calculate number of carry digits */ | |
for (j = 0; carry > 0; j++, carry /= 10) | |
; | |
/* Print the rest */ | |
for (i = 0; i < 10-j; i++) | |
printf("%d", digits[i]); | |
printf("\n"); | |
return 0; | |
} | |
int sum_digits(int n) { | |
int i, sum = 0; | |
for (i = 0; i < LINES; i++) | |
sum += numbers[i][n]; | |
return sum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment