project euler 8th problem

I give up, I can't find a flaw in my code.
It's supposed to "find the greatest product of five consecutive digits in the 1000-digit number." The output is 31752, which doesn't appear to be correct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 #include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string x= "731671765313306249...963450"; // the number is so long it doesn't appear to fit here
int sum=1, n=0; int y, max=0; int i=0;
for (i=0; i<=999; i=i+5) {
for (n=i; n<=i+4; n++) {
stringstream convert;
convert << x[n];
convert >> y;
sum=sum*y;}
if (sum>max) max=sum;
sum=1;
}
cout << max;
}
Last edited on
I would like to mention you should work on proper indentations. inside each curly brace it the code moves over one tab ( 4-6 spaces ). Also you should get in the habit with using < in your for loops instead of <= there are very seldom cases where you should use <= instead of < it will help with arrays. Also shouldn't it be product and not sum? Also on line 15 what happens if it is they are equal? It will be reset.

Here is how I did this problem a long time ago but feel free to look at it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <fstream>
#include <vector>

int main()
{
    std::vector<unsigned short> numbers( 0 );
    unsigned short temp( 0u ) , result( 0u ) , i( 0u );
    std::ifstream in( "data.txt" );
    while( in.good() )
    {
        temp = in.get() - '0';
        if( temp < 10 ) numbers.emplace_back( temp );
    }

    while( i + 4 < numbers.size() )
    {
    	temp = 1;
    	for( int j = 0; j < 5; ++j )
    		temp *= numbers[ i + j ];
        if( result < temp ) result = temp;
        ++i;
    }

    std::cout << result << std::endl;
}


The only problems I can think of with your code is there might be a problem with your for loops or maybe you copied the string wrong.

*edit I have no idea what I was thinking when I put that if statement on line 13 in my code. That was so long ago
Last edited on
Topic archived. No new replies allowed.