Given a positive integer N, count number of ways to write N as a sum of three numbers. For numbers which are not expressible print -1.
Input: N = 4
( 1 + 1 + 2 ) = 4
( 1 + 2 + 1 ) = 4
( 2 + 1 + 1 ) = 4.
So in total, there are 3 ways.
Input: N = 5
( 1 + 1 + 3 ) = 5
( 1 + 3 + 1 ) = 5
( 3 + 1 + 1 ) = 5
( 1 + 2 + 2 ) = 5
( 2 + 2 + 1 ) = 5
( 2 + 1 + 2 ) = 5.
So in total, there are 6 ways
Approach: To solve the problem mentioned above if we take a closer look we will observe a pattern in solution to the question. For all the numbers that are greater than 2 we get a series 3, 6, 10, 15, 25 and so on, which is nothing but the sum of first N-1 natural numbers.
Below is the implementation of the above approach:
Time Complexity: 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.
- Count ways to split a Binary String into three substrings having equal count of zeros
- Count of ways to split an Array into three contiguous Subarrays having increasing Sum
- Ways to write N as sum of two or more positive integers | Set-2
- Print all possible ways to write N as sum of two or more positive integers
- Number of quadruples where the first three terms are in AP and last three terms are in GP
- Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
- Count three-digit numbers having difference X with its reverse
- Count ways to express a number as sum of consecutive numbers
- Count ways to express a number as sum of exactly two numbers
- Count of ways in which N can be represented as sum of Fibonacci numbers without repetition
- Find three prime numbers with given sum
- Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
- Write a function that generates one of 3 numbers according to given probabilities
- Write a program to add two numbers in base 14
- Count number of ways to arrange first N numbers
- Prove that atleast one of three consecutive even numbers is divisible by 6
- Swap three numbers in cycle
- Smallest n digit number divisible by given three numbers
- Check whether given three numbers are adjacent primes
- Probability for three randomly chosen numbers to be in AP
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.