Given a number N, write a function to express N as sum of two or more consecutive positive numbers. If there is no solution, output -1. If there are multiple solution, then print one of them.
Input : N = 10 Output : 4 + 3 + 2 + 1 Input : N = 8 Output : -1 Input : N = 24 Output : 9 + 8 + 7
Sum of first n natural numbers = n * (n + 1)/2 Sum of first (n + k) numbers = (n + k) * (n + k + 1)/2 If N is sum of k consecutive numbers, then following must be true. N = [(n+k)(n+k+1) - n(n+1)] / 2 OR 2 * N = [(n+k)(n+k+1) - n(n+1)]
Below is the implementation based on above idea.
12 = 3 + 4 + 5
This article is contributed by Roshni Agarwal. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- Count ways to express a number as sum of consecutive numbers
- Express an odd number as sum of prime numbers
- Count ways to express a number as sum of exactly two numbers
- Find the number of consecutive zero at the end after multiplying n numbers
- Check if a number can be expressed as a sum of consecutive numbers
- Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
- Minimum numbers needed to express every integer below N as a sum
- Minimum number of distinct powers of 2 required to express a given binary number
- Fibbinary Numbers (No consecutive 1s in binary)
- Expressing factorial n as sum of consecutive numbers
- 1 to n bit numbers with no consecutive 1s in binary representation.
- Sum of Hamming difference of consecutive numbers from 0 to N | Set 2
- Ways to express a number as product of two different factors
- Minimum number of palindromes required to express N as a sum | Set 1
- Minimum number of palindromes required to express N as a sum | Set 2
- Count ways to express even number ‘n’ as sum of even integers
- Prove that atleast one of three consecutive even numbers is divisible by 6
- Count of N-digit numbers in base K with no two consecutive zeroes
- Count of N digit Numbers whose sum of every K consecutive digits is equal
- Count of N digit Numbers whose sum of every K consecutive digits is equal | Set 2
Improved By : nitin mittal