Skip to main content

Project Euler Solution 12

Problem Statement#

What is the value of the first triangle number to have over five hundred divisors?

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?

Solution#

As given in the problem, nth triangle number is generated by adding first n natural numbers. The sum of first n natural numbers or the nth triangular number is given by

n * (n + 1) / 2

The factors occur in pairs and its enough to find the factors up to the square root of the triangle number and increment the count by two each time a factor is found.

Implementation#

#include <stdio.h>#include <math.h>
using namespace std;
int main(){    long n, tri_number, count;    n = 1;    while (n != 0)    {        tri_number = n *(n + 1) / 2;        count = 2;        for (int k = 2; k <= sqrt(tri_number); k++)        {            if ((tri_number % k) == 0)            {                count += 2;            }            if (count >= 500)            {                printf("%d", tri_number);                return 0;            }        }        n++;    }    return 0;}

Sample Output#

Sample Output