Task 14 - C - Getting wrong solution and unable to locate why

Back to Problem Solutions forum

John-Russell     2015-04-12 01:33:14

Here is my code:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    unsigned long long base = 0;

    ifstream input("input.txt");
    ofstream output("output.txt");

    input >> base;

    while (!input.eof()) {
        char action = '0';
        long int number = 0;

        input >> action;
        input >> number;

        switch(action) {
        case '+':
            base += number;
            break;
        case '*':
            base *= number;
            break;
        case '%':
            base %= number;
            break;
        };
    }

    output << base;

    input.close();
    output.close();
}

I'm absolutely stuck on this task and can't seem to locate the cause of the wrong answer. It works on the example test data, but not on the actual test data that I'm given.

Quandray     2015-04-12 07:29:19
User avatar

At some point in the calculation, the intermediate result is probably too big for an unsigned long long.

Intermediate results don't need to be so large. This exercise was created to show you that the modulo could be applied after any (possibly all) of the intermediate operations.

John-Russell     2015-04-12 20:57:23

Now that you say that, it seems somewhat obvious that the modulo can be applied to all steps to prevent the number from getting too big. Thanks a bunch!

Please login and solve 5 problems to be able to post at forum