Given two integers N and K, the task is to find K consecutive integers such that their sum if N.
Note: If there is no such K integers print -1.
Input: N = 15, K = 5
Output: 1 2 3 4 5
N can be represented as sum of 5 consecutive integers as follows –
=> N => 1 + 2 + 3 + 4 + 5 = 15
Input: N = 33, K = 6
Output: 3 4 5 6 7 8
N can be represented as sum of 6 consecutive integers as follows –
=> N => 3 + 4 + 5 + 6 + 7 + 8 = 33
Naive Approach: A simple solution is to run a loop from i = 0 to N – (K – 1) to check if K consecutive integers starting from i is having sum as N.
Efficient Approach: The idea is to use Arithmetic Progression to solve this problem, where sum of K terms of arithmetic progression with common difference is 1 can be defined as follows –
- Sum of K Terms –
- Solving the equation further to get the first term possible
- Here aK is the Kth term which can be written as a1 + K – 1
- Finally, check the first term computed is an integer, If yes then K consecutive number exists whose sum if N.
Below is the implementation of the above approach:
3 4 5 6 7 8
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Number expressed as sum of five consecutive integers
- Check if N can be represented as sum of squares of two consecutive integers
- Check if a number can be written as sum of three consecutive integers
- Remove two consecutive integers from 1 to N to make sum equal to S
- Minimum increments to convert to an array of consecutive integers
- Find two integers A and B such that A ^ N = A + N and B ^ N = B + N
- Find N distinct integers with zero sum
- Find the prime P using given four integers
- Find N distinct integers with sum N
- Find N integers with given difference between product and sum
- Find K distinct positive odd integers with sum N
- Find any K distinct odd integers such that their sum is equal to N
- Find the first N integers such that the sum of their digits is equal to 10
- Find if it is possible to choose subarray that it contains exactly K even integers
- Find three integers less than or equal to N such that their LCM is maximum
- Find the number of integers from 1 to n which contains digits 0's and 1's only
- Find sum in range L to R in given sequence of integers
- Find the number of consecutive zero at the end after multiplying n numbers
- Find Prime Adam integers in the given range [L, R]
- Find n positive integers that satisfy the given equations
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.