HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Project Euler #8 - "largest product in a series"

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
productlargestprojecteulerseries

Problem

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 
#include 
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  max_product) {
        max_product = product;
      }
    }
    zero_for_next--;
  }
  cout << max_product << endl;
}

Solution

-
This is probably not a good idea:

while (ifs.good()) {
  string line;
  getline(ifs, line);
  series += line;
}


You should be checking the stream itself, not the current state of the stream. This can be done by putting the stream read (getline() in this case) inside the loop statement.

Also, as getline() (which uses line) will be moved out of scope after this change, you'll need to initialize line before the loop.

string line;

while (getline(ifs, line)) {
    series += line;
}


This will both attempt the read and determine if it was successful. If it wasn't, specifically if the end of the file has been reached, then it will fail, and the loop will terminate. See this answer for more info.

-
Your compiler should've warned you about this type-mismatch:

for (size_t i = 0; i < DIGITS_IN_PRODUCT; i++)


The loop counter type should be an int to match the constant's type.

Code Snippets

while (ifs.good()) {
  string line;
  getline(ifs, line);
  series += line;
}
string line;

while (getline(ifs, line)) {
    series += line;
}
for (size_t i = 0; i < DIGITS_IN_PRODUCT; i++)

Context

StackExchange Code Review Q#64615, answer score: 3

Revisions (0)

No revisions yet.