I've just done Problem 12 of Project Euler:
What is the value of the first triangle number to have over five hundred divisors?
The \$N\$'th triangle number is the sum of all natural numbers from \$1\$ to \$N\$, for example, the 5th triangle number is \$1 + 2 + 3 + 4 + 5 = 15\$
I get the correct answer in around 2.5 seconds.
I was wondering if anyone could suggest anything that could improve the performance of the program, or improve the code in general.
public class Problem12 {
public static void main(String[] args) {
double startTime = System.currentTimeMillis();
run();
double endTime = System.currentTimeMillis();
System.out.println("Took "+((endTime - startTime) / 1000)+" seconds");
}
public static void run() {
boolean go = true;
long number = 1;
long nextNum = 2;
int maxDivisors = 500;
while (go) {
if (countDivisors(number) > maxDivisors) {
System.out.println("The first triangle number with over "+maxDivisors+" divisors is: "+number);
go = false;
}
else {
number += nextNum;
nextNum++;
}
}
}
public static long countDivisors(long number) {
long divisors = 0;
for (int i = 1; i*i <= number; i++) {
if (number % i == 0) {
divisors+=2;
}
}
return divisors;
}
}