![]() |
VOOZH | about |
Given a range, find the XOR of the smallest and largest triangular numbers within that range.
A triangular number is a number that can be represented as the sum of consecutive positive integers starting from 1. In other words, a triangular number is the sum of the first n natural numbers, where n is a positive integer. The formula for the nth triangular number is: Tn = 1 + 2 + 3 + ... + n = n(n+1)/2
For example, the first few triangular numbers are:
T1 = 1
T2 = 1 + 2 = 3
T3 = 1 + 2 + 3 = 6
T4 = 1 + 2 + 3 + 4 = 10
Examples:
Input: Range [60, 195]
Output: 252
Explanation: Smallest triangular number in the given range is 66, and the largest triangular number in the given range is 190. The XOR of 66 and 190 is 252.Input: Range [100, 280]
Output: 381
Explanation: Smallest triangular number in the given range is 105, and the largest triangular number in the given range is 276. The XOR of 105 and 276 is 381.
Approach: This can be solved with the following idea:
The idea behind this approach is to first define a function to find the nth triangular number using the formula n*(n+1)/2. Then, we define two functions to find the smallest and largest triangular numbers within a given range. To find the smallest triangular number within the range, we simply iterate through the triangular numbers until we find the first triangular number that is greater than or equal to the lower bound, and return that triangular number if it is also less than or equal to the upper bound. If there is no triangular number within the range, we return -1. To find the largest triangular number within the range, we again iterate through the triangular numbers, but this time we return the previous triangular number when we find the first triangular number that is greater than the upper bound. This is because the previous triangular number is the largest triangular number within the range. If there is no triangular number within the range, we return 0.
Steps of the above approach:
Below is the implementation of the above approach:
381
Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)