-1

Here's a link to the problem I'm trying to solve: https://projecteuler.net/problem=8.

I've written a code that seems to work well while I'm calculating a product of anything from 1 to 12 (included) consecutive digits. For example the biggest product of 12 adjacent digits I get is 1792336896, which seems logical as it's less than 9^12.

However, when I put 13 instead of 12 in my code, the answer I get is 18446744073195294960 which is way out of proportion. I've been looking at this a couple of days now, and I just can't see where I went wrong. I would really appreciate if anyone could look into it.

Here's my code:

#include <iostream>
#include <fstream>

using namespace std;

int numbers[1000];
string line;
string numb;
uint64_t product=0;

void convert(){

    for (int i = 0 ; i < numb.length() ; i++)
    {
        numbers[i] = numb[i] - '0';
    }
}

void calculate_lines(){

    int digits = 13;
    for (int i=0;i<numb.length()-digits;i++){
        int temp=1;
        for (int j=i;j<digits+i;j++){
            if (numbers[j] == 0){
                i+=digits;
                break;
            }
            temp=temp*numbers[j];
        }

        if (temp>=product){
            product=temp;

        }
    }


}

void read_lines(){
    ifstream infile;
    infile.open("numbers.txt");
    if (infile.is_open())
    {
        while (getline(infile,line))
        {
            numb+=line;
        }
    infile.close();
    }
}

int main()
{
    read_lines();
    convert();
    calculate_lines();
    cout << product << endl;
    return 0;
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
AlexKey
  • 16
  • 1

1 Answers1

2

You calculate the product with the variable int temp. This isn't large enough to contain a product of 13 digits, so it overflows. It becomes a negative value, which later becomes a very large positive value when converted to uint64_t.

While the variable that holds the final result product is a uint64_t, you need to make sure that intermediate values are stored in large enough variables. You need temp to be uint64_t as well.

interjay
  • 107,303
  • 21
  • 270
  • 254