Java solution to Project Euler Problem 12

Problem 12:

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:
01: 1
03: 1,3
06: 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?

Running time: 1325ms (1.3 sec)

Assessment: There’s probably a better/faster way to do this.

public class Problem012
{
	private static int countFactors(int f)
	{
		int factors = 0;
 
		for (int i = 1; i <= Math.sqrt(f); i++)
		{
			if (f % i == 0)
				factors += 2;
		}
 
		return factors;
	}
 
	public static void main(String[] args)
	{
		long begin = System.currentTimeMillis();
		int iter = 1;
		int size = 1;
		int NumFactors = 0;
 
		while (NumFactors <= 500)
		{
			NumFactors = countFactors(size);
			iter++;
			size += iter;
		}
 
		System.out.println(size-iter);
		long end = System.currentTimeMillis();
		System.out.println(end-begin + "ms");
	}
}

3 thoughts on “Java solution to Project Euler Problem 12

  1. This program has a problem: The number of factors of the program computed is wrong when “size” can be squared.

  2. thanks .and
    int factors = 0;
    if(f==1) return 1; //you need to add it
    for (int i = 1; i <= Math.sqrt(f); i++)
    {
    if (f % i == 0)
    factors += 2;
    }

    return factors;

Leave a Reply

Your email address will not be published. Required fields are marked *