CPlusPlus - gregorymorrison/euler1 GitHub Wiki

C++ is one of the most popular object-oriented languages. It debuted in 1983 and is a superset of the C language, with the addition of OOP. I wanted to write a representative version of Euler1 in C++, but I failed. It turns out that this is a stupid idea - OOP is just overkill for what is essentially a simple function. There is no benefit to construing a simple function in terms of classes. This is the problem with languages like Java and Haskell that rigidly enforce purity - there will always be edge cases that require you to subvert the paradigm.

Anyway, here is my attempt - a class with members, a constructor, and a method. Obviously overkill, but it is cleanly defined. I haven't done C++ in years although I know it well, so it took me maybe 10 minutes to write the following:

// Euler1 in C++
#include <iostream>

class Euler1 {
    private:
        int size;
        int result;

        bool isMultipleOfThree(int n) {
            return n % 3 == 0;
        }

        bool isMultipleOfFive(int n) {
            return n % 5 == 0;
        }

    public:
        Euler1(int size) {
            this->size = size;
            this->result = 0;
        }

        void solve() {
            for (int i = 0; i < size; i++) {
                if (isMultipleOfThree(i) || isMultipleOfFive(i)) {
                    result += i;
                }
            }
        }

        int getResult() {
            return result;
        }
};

int main () {
    Euler1 euler1(1000);

    euler1.solve();

    std::cout << "Euler1 = " << euler1.getResult();
    return 0;
}

To run this, I used the venerable GCC compiler. Compile to object code, enable execute permissions on the resultant object file, then execute:

$ g++ euler1.cpp -o euler1 
$ chmod 777 euler1
$ ./euler1.exe
Euler1 = 233168
⚠️ **GitHub.com Fallback** ⚠️