-
Notifications
You must be signed in to change notification settings - Fork 2
Java
I wanted to write a representative version of Euler1 in Java, a pure Object-Oriented language developed in 1995 by Sun, 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. Java is my bread and butter language, so it took me only a minute to write the following:
// Euler1 in Java
class Euler1 {
private int size;
private int result;
public Euler1(int size) {
this.size = size;
}
public void solve() {
result = 0;
for (int i=0; i<size; i++) {
if (i%3==0 || i%5==0) {
result += i;
}
}
}
public int getResult() {
return result;
}
public static void main(String[] args) {
Euler1 euler1 = new Euler1(1000);
euler1.solve();
System.out.println(euler1.getResult());
}
}
To run this, compile to bytecode using the java compiler, then execute the resultant class file:
$ javac Euler1.java
$ java Euler1
233168
Return home