Long (really long) number
Indeed.
So, as probably someone understood from my previous post, I'm trying to work my way out of the easiest problems listed in projecteuler.net, in an attempt to improve my coding skills and my knowledge of the C language. Anyway, I'm stuck again, after I completed a couple of other problems since your last help, and here's why.
The point of the code that follows is to calculate a really big sum: one hundred 50-digits numbers have to be summed. I thought a bit about it and I came to this conclusion: I could copy-paste the values in a file, and from there I could loop as follows: read one string, convert it to a integer, sum and then proceed to the next value. Perhaps you already spotted the problem - I can't find a way to store the value, 'cause nothing I've found is big enough for a 50-digits number. The sad thing is that it dawned me all together when I've found this. If I understood it correctly, it says that the maximum value that could be stored is 18,446,744,073,709,551,615, an unsigned long long. Which is exactly what I'm using, and that's why when I convert from string to integer I receive unpleasant results.
Code:
/*Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
*SEE FILE ATTACHED** */
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
int main(int argc, char *argv[]) {
int i;
uintmax_t pivot=0, sum=0;
char ascii_num[50], ascii_sum[sizeof(uintmax_t)*8]; //this last one is gonna be 64
FILE *fp;
//File opening
fp=fopen("problem13.txt", "r");
if (fp==NULL) {
printf("Error: could not open file problem13.txt.\nPress any key to exit.\n");
getch();
return (1);
}
while (fgets(ascii_num, 50, fp) != NULL) {
pivot = atoll(ascii_num);
sum +=pivot;
}
itoa(sum, ascii_sum, 10);
for(i=0; i<10; i++) {
printf("%d", ascii_sum[i]);
}
fclose(fp);
printf("\nPress any key to continue.\n");
getch();
return (0);
}
I tried in several different ways to work around the conversion from string to integer - atoll is just the last one in chronological order.
My main point is: is this algorithm flawed, or can this work out the way I want? I can see at least one other problem down the road (that atoi down there, for the second conversion), so I'm not really sure this is the best way to do it. Actually, I'm sure this is not it - should I rethink my solution? Any ideas?