Wenn ich in diesem Code ein Objekt in der mainMethode erstelle und diese Objektmethode dann ff.twentyDivCount(i)aufrufe : (wird in 16010 ms ausgeführt), wird sie viel schneller ausgeführt als mit dieser Anmerkung: twentyDivCount(i)(wird in 59516 ms ausgeführt). Wenn ich es ausführe, ohne ein Objekt zu erstellen, mache ich die Methode natürlich statisch, damit sie hauptsächlich aufgerufen werden kann.
public class ProblemFive {
// Counts the number of numbers that the entry is evenly divisible by, as max is 20
int twentyDivCount(int a) { // Change to static int.... when using it directly
int count = 0;
for (int i = 1; i<21; i++) {
if (a % i == 0) {
count++;
}
}
return count;
}
public static void main(String[] args) {
long startT = System.currentTimeMillis();;
int start = 500000000;
int result = start;
ProblemFive ff = new ProblemFive();
for (int i = start; i > 0; i--) {
int temp = ff.twentyDivCount(i); // Faster way
// twentyDivCount(i) - slower
if (temp == 20) {
result = i;
System.out.println(result);
}
}
System.out.println(result);
long end = System.currentTimeMillis();;
System.out.println((end - startT) + " ms");
}
}
BEARBEITEN: Bisher scheinen verschiedene Maschinen unterschiedliche Ergebnisse zu liefern, aber bei Verwendung von JRE 1.8. * Scheint das ursprüngliche Ergebnis konsistent reproduziert zu werden.
+PrintCompilation +PrintInlininggezeigt