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, …
Input: N = 2
6 is the first triangular number with more than 2 factors.
Input: N = 4
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.
- When X is even, then X/2 and (X+1) will be considered as two numbers whose prime factorisation is to be find out.
- When X is odd, then X and (X+1)/2 will be considered as two numbers whose prime factorisation is to be find out.
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.
- Find sum of inverse of the divisors when sum of divisors and the number is given
- Find sum of divisors of all the divisors of a natural number
- Querying maximum number of divisors that a number in a given range has
- Find the number of integers x in range (1,N) for which x and x+1 have same number of divisors
- Find the largest good number in the divisors of given number N
- Number of divisors of a given number N which are divisible by K
- Total number of divisors for a given number
- Centered triangular number
- Triangular Matchstick Number
- Centered triangular number in PL/SQL
- Smallest triangular number larger than p
- Squared triangular number (Sum of cubes)
- Program to print triangular number series till n
- Find the sum of the number of divisors
- Sum of all the prime divisors of a number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.