This code works when compiled on gcc 4.8.2.
I would appreciate any comments on my style and the readability of my code, and any improvements that I could make to make the code more readable and/or performant.
Problem: Largest product in a series
Solution:
/* * file: pe_008.cc * title: Largest product in a grid * date: October 2, 2014 * * note: The largest possible product of 13 consecutive digits * in a decimal number is 9^13. log_2(9^13) = ~41.2, so we * will need to use a 64-bit integer to represent the product. * * note 2: Since some of the elements in the series are 0. The product * of the digits in the 13-digit subseries will be 0 if any of * the elements are 0. This means that if we see a 0, we can * skip ahead by 13 digits, but we have to cache the nonzero * digits that we skip over. */
#include <fstream>
#include <iostream>
using namespace std;
const int DIGITS_IN_PRODUCT = 13;
int main() {
// read series.txt into a string without newline characters
ifstream ifs("../series.txt");
string series;
while (ifs.good()) {
string line;
getline(ifs, line);
series += line;
}
ifs.close();
// take the product of the first 13 elements in the string
uint64_t product = 1;
uint64_t max_product;
uint8_t product_digits[DIGITS_IN_PRODUCT];
for (size_t i = 0; i < DIGITS_IN_PRODUCT; i++) {
product_digits[i] = series[i] - '0';
product *= product_digits[i];
}
max_product = product;
int zero_for_next = 0;
for (size_t i = DIGITS_IN_PRODUCT; i < series.length(); i++) {
// use the modulo operator to minimize overwrites
product_digits[i % DIGITS_IN_PRODUCT] = series[i] - '0';
if (series[i] == '0') {
zero_for_next = DIGITS_IN_PRODUCT;
continue;
} else if (zero_for_next < 1) {
product = 1;
// the order in which the product is taken is not important
for (uint8_t digit : product_digits) {
product *= digit;
}
if (product > max_product) {
max_product = product;
}
}
zero_for_next--;
}
cout << max_product << endl;
}