![]() |
VOOZH | about |
Given a number N, find the first triangular number whose number of divisors exceeds N. Triangular numbers are sums of natural numbers, i. e., of the form x*(x+1)/2. First few triangular numbers are 1, 3, 6, 10, 15, 21, 28, ...
Examples:
Input: N = 2
Output: 6
6 is the first triangular number with more than 2 factors.
Input: N = 4
Output: 28
A naive solution is to iterate for every triangular number and count the number of divisors using the Sieve method. At any moment if the number of divisors exceeds the given number N, then we get our answer. If the triangular number which has more than N divisors is X, then the time complexity will be O(X * sqrt(X)) as pre-processing of primes is not possible in case of larger triangular numbers. The naive solution is important to understand in order to solve the problem more efficiently.
An efficient solution will be to use the fact that the triangular number's formula is x*(x+1)/2. The property that we will use is that k and k+1 are coprimes. We know that two co-primes have a distinct set of prime factors. There will be two cases when X is even and odd.
Hence the problem has been reduced to the just finding out prime factorization of smaller numbers, which reduces the time complexity significantly. We can reuse the prime factorization for x+1 in the subsequent iterations, and thus factorizing one number in each iteration will do. Iterating till the number of divisors exceeds N and considering the case of even and odd will give us the answer.
Below is the implementation of the above approach.
28
Time Complexity: O(N*logN),
Auxiliary Space: O(105), as we are using extra space for primer array.