The statement is as follows :
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
My implementation :
import java.util.ArrayList;
import java.util.HashMap;
public class Euler_12{
// This function finds the prime factorization
// of a given number
public static int getDivisors(int number){
ArrayList<Integer> list = new ArrayList<Integer>();
while(number%2==0){
list.add(2);
number/=2;
}
for(int i = 3; i<=Math.sqrt(number); i++){
while(number%i==0){
list.add(i);
number/=i;
}
}
if(number>2){
list.add(number);
}
return findDivisors(list);
}
// Uses HashMap to convert multiples in form of
// 2 2 2 2 4 4 to 2^4 x 4^2
public static int findDivisors(ArrayList<Integer> list){
int result = 1;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i : list){
if(map.containsKey(i))
map.put(i, map.get(i)+1);
else
map.put(i, 1);
}
// Better take a look at [1]
// on why I did this
for(int i : map.keySet()){
result = result * (map.get(i) + 1);
}
// the result is number of divisors
return result;
}
public static int number = 0;
public static int sequence = 1;
// Returns the next Triangular number
public static int nextTraingularNumber(){
int temp = number + sequence;
number = temp;
sequence++;
return temp;
}
public static void main(String[] args) {
while(true){
int i = nextTraingularNumber();
if(getDivisors(i)>500){
System.out.println("Found : " + i);
break;
}
}
}
}
It finds the answer in 0.812 seconds. Looking for improvements, suggestions are welcomed
i<=Math.sqrt(number)
could bei*i <= number
for efficiency. \$\endgroup\$