-2

I am having some sort of a problem in a task from https://projecteuler.net/problem=8, (finding highest product of 13 consecutive numbers from a 1000-number string) where up to some point the program gives me predictable results and then the function returns a number very close to the unsigned long long int range. The point where it occurs depends on the values which were read, for instance if the string of numbers consisted mostly of 8s and 9s, it would happen sooner than it would if it had only 5s and 6s. Why does it happen?

#include <iostream>
#include <fstream>

using namespace std;


int product (int res, int a, char buffer[]){
for (int i = 0; i < a; i++){
//simple char to int conversion
res*=(buffer[i] - '0');
}

return res;
}

int main () {
char check;
int res = 1;
fstream plik;
plik.open ("8.txt");
unsigned long long int high;
unsigned long long int result;
//main function in the program
if (plik.good()){
    char buffer [13];
    for (int i = 0; i < 13; i++){
        plik >> buffer[i];
    }
    result = product (res, 13, buffer);
    high = result;
    cout << high << endl;
    //the main checking loop
    while (!plik.eof()){
    //just an interruption to make it possible to view consecutive products
    //the iteration in the buffer
    for (int i = 0; i < 12; i++){
    buffer[i] = buffer[i+1];
    }
    plik >> buffer[12];
    result = product (res, 13, buffer);
    //comparison between the current product and highest one
    if (high < result){
    high = result;
    }
    cin >> check;
    cout << high << endl;
    //again a tool for checking where the problem arises
    for (int i = 0; i < 13; i++){
        cout << buffer[i] << "  ";
    }
    cout << endl;
    }
    plik.close();
    cout << high << endl;
}

return 0;

}

The program prints out the currently highest product and all the numbers currently contained in the array. It looks like this: The error

1 Answers1

1

Use unsigned long long int instead of int to calculate the product. The product of 13 digits can easily become larger than the largest int.

Frank Puffer
  • 7,773
  • 2
  • 16
  • 39