Reputation: 1
I'm working on Problem 8 of Project Euler where I have to find the largest product of 13 consecutive digits from a given 1000 digit number. I stored that number in a text file and then inputted it in my source code. My code compiles and runs, but my answer seems to be incorrect. Can anybody help me figure out where the error is?
Here is my code:
#include <stdio.h>
int main()
{
int x,ar[1000],i = 0,prod = 0,tmp=1;
FILE* fp = fopen("file.txt","r");
if (fp == NULL)
{
printf("error");
return 1;
}
while((x = fgetc(fp)) != EOF)
{
ar[i] = x;
i++;
}
/*for(int m =0;m<999;m++)
{
printf("%d",ar[m]);
}*/
for(int j =0;j <= 986;j++)
{
for(int k=j;k<j+13;k++)
{
tmp = tmp * ar[k];
}
if(tmp > prod)
{
prod = tmp;
}
}
printf("%i",prod);
return 0;
}
Upvotes: 0
Views: 167
Reputation: 14751
The product of 13 consecutive digits may exceeds range of int
which you're using for tmp
. You need data types that supports a wider range. Maybe 64bit ones like unsigned long long
would do.
Also as @deviantfan has pointed out, you're reading characters, and '0'
as an character is not the same thing as a number 0
. Read about ASCII.
Another problem is that the logic of tmp
is not correct: you didn't re-initialize it to 1
after each 13 step loop.
Reply to your comment: I suppose in this case the best solution is to read the data as characters, however after that you could convert the ASCII to integer, e.g.:
while((x = fgetc(fp)) != EOF)
{
// x - '0' does the conversion,
// e.g. the expression obtains 0 from '0' - '0', and 5 from '5' - '0'
ar[i] = x - '0';
i++;
}
Upvotes: 3
Reputation: 180316
You are taking the product of digit chars, not of the digits they represent. '1' != 1.
Upvotes: 2