-3

https://projecteuler.net/problem=13

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.

I try to solve it using C++ in Xcode. I saved the numbers in a file and built it successfully but got the wrong answer. Here is my code:

#include <fstream>
#include <iostream>
using namespace std;

int main(void) {
  double sum = 1;
  double num;
  ifstream fin("/Users/pwd/programs/projectEuler13/num.txt");

  while (fin) {
    fin >> num;
    sum += num;
  }
    fin.close();
  cout.precision(12);
  cout << sum << endl;
  return 0;
}

I got the result: 5.59087976462e+51

So first 10 digits of the sum: 5590879764. But it is wrong. What is wrong with my code?

pjpj
  • 443
  • 1
  • 4
  • 20
  • double? And *you* need to cut it down to 10 digits. – deviantfan May 28 '16 at 13:25
  • Uh, what part is wrong? Maybe I don't understand the question. It asks you for the first 10 digits of the sum. You got 5.59087976462e+51 as the sum. What are the first 10 digits of that? – Cody Gray May 28 '16 at 13:25
  • @CodyGray Isn't that scientific notation? – pjpj May 28 '16 at 13:35
  • 1
    Hint: how do you add a whole bunch of numbers by hand, on paper? (This is very close to being a trick question - you only need to remember what you did in primary school and think slightly outside the box.) – molbdnilo May 28 '16 at 14:48

1 Answers1

2

Several issues I can see:

  1. Starting the sum from 1, although this is highly unlikely to change your result.

  2. Using floating-point introduces inaccuracies. More likely to change your result but in this case it probably still won't, because you only need 10 significant digits.

  3. The most serious problem: Incorrectly looping over the input. See Why is iostream::eof inside a loop condition considered wrong?. This will probably cause you to add the last number twice. The correct way to loop over an input stream is:

    while (fin >> val) {
         //do something with val.
    }
    
Community
  • 1
  • 1
interjay
  • 97,531
  • 20
  • 242
  • 238
  • Yeah you are right, but in this case how can I avoid floating point? – pjpj May 28 '16 at 13:38
  • You can use a big-number library like GMP, or implement long-addition yourself by representing each number as an array of digits. But in this case floating point is probably good enough. – interjay May 28 '16 at 14:09
  • It does give the correct answer to enough significant digits to solve the probelm, given the fix in #3. – Mark Tolonen May 29 '16 at 00:54