Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Project Euler #12. What is the value of the first triangle number to have over five hundred divisors? I felt that this problem was easier than the last two, but I got stuck on line 29 and had to look up online for help. I want to come back to this problem and make it smoother. It is about 1.1 seconds, but it should be able to run at like 50ms wi…
public class TriangleNumber {
private int numDivisors;
public TriangleNumber(int numDivisors){ //takes in how many divisors
this.numDivisors = numDivisors;
}
public int firstOccurance(){ //returns the first occurance of the number of divisors you want the triangle number to have
int i = 1;
int triNum = 0;
while(true){
if(divisorCounter(triNum) > this.numDivisors){ //when divisors for the triangle number
break;
}
triNum += i; //goes to next triangle num
++i;
}
return triNum;
}
public int divisorCounter(int number){ //figures number of divisors
int counter = 0;
for(int i = 1; i <= Math.sqrt(number); ++i){
if(number % i == 0){
counter += 2;
}
}
if(Math.sqrt(number) * Math.sqrt(number) == number){ //kept going too high on the triangle number, found that this was the reason
counter--;
}
return counter; //returns number of divisors
}
public static void main(String[] args){
long begin = System.currentTimeMillis();
TriangleNumber tri = new TriangleNumber(500);
System.out.println(tri.firstOccurance());
System.out.println(System.currentTimeMillis() - begin);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment