Given an integer N, the task is to check if N is the sum of a pair of integers which can be expressed as the sum of first X natural numbers, where X can be any positive integer. If satisfies the required condition. Print “YES”. Otherwise, print “NO”.
Input: N = 25
=> 10 + 15 = 25
Since 10 and 15 are the sum of first 4 and 5 natural numbers respectively, the answer is YES.
Input: N = 512
Approach: The idea is to choose a sum of natural numbers M which is less than equal to N and check if M and N – M are the sums of the sequence of the first few natural numbers. Follow the steps below to solve the problem:
- Iterate over a loop to calculate the sum of K natural numbers:
Sum of K natural numbers = K * (K + 1) / 2
- Then, calculate the remaining sum and check if the sum is the sum by the following equation:
Y = N – Sum of K Natural number
=> Y = N – (K * (K + 1) / 2)
- Check if the number calculated above satisfies the required condition by calculating the square root of the twice of the number and check if the product of consecutive numbers is equal to the twice of the number.
M * (M + 1) == 2 * Y, where M = √ (2 * Y)
- If the above condition is satisfied, print “YES”. Otherwise, print “NO”.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.