Project Euler : Problem 12 - Highly divisible triangular number

2 minute read

Problem Statement : Highly divisible triangular number

Problem 12 : The sequence of triangle numbers is generated by adding the natural numbers. So the th triangle number would be . The first ten terms would be:

Let us list the factors of the first seven triangle numbers:

We can see that 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?

Concept and Theory

Triangular Numbers : The triangular number is the sum of continuous natural numbers from to , below is the formula,

As we all know that is the only common factor between two consecutive numbers. Hence one can find the factor of and or and , and multiply them to get the total factor count. This will save us some time and also we will be able to avoid factoring a large number.

We have covered Prime Factorization methods in previous post.

Code for finding Nth Triangular Number

/**
 * A function to get the Nth Triangular number
 *
 * @param num Given number to test
 * @return return the nth Triangular number
 */
public static long getNthTriangularNumber(long num) {
  return (num * (num + 1)) / 2;
}

Code for this problem

public static int FactorCount(int limit) {
    int cnt = 0;
    int answer = 0;
    for (int i = 1; cnt <= limit; i++){
        if (i % 2 == 0) cnt = count(i / 2) * count (i+1);
        else cnt = count(i) * count((i+1)/2);
        //System.out.println("" + i + "\t" + cnt);
        if (cnt > limit){
            answer = i;
            break;
        }
    }
    return (answer*(answer+1))/2;
}



static int  count(int n) {
    int result = 0;
    for (int i = 1; i*i <= n; i++){
        if (n % i == 0) {
            result+=2;
            if (n / i == i)
                result--;
        }
    }
    return result;
}

Test Your Skills

Wanna try a harder version of the above problem ? Check this HackerRank problem.

Solution

The solution will remain same as given in the above mentioned post, , you just need to call it for each test case.

References and Further Readings

Leave a Comment

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

Loading...