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 number of ways to arrange first N numbers
- Count of ways to make Array sum even by removing only one element
- Swap three numbers in cycle
- C program to Find the Largest Number Among Three Numbers
- Program to find the common ratio of three numbers
- Product of Complex Numbers using three Multiplication Operation
- Maximize count of equal numbers in Array of numbers upto N by replacing pairs with their sum
- Count of elements which are second smallest among three consecutive elements
- Check if a number can be written as sum of three consecutive integers
- 7 different ways to Add Two Numbers in C/C++
- Count ways to divide C in two parts and add to A and B to make A strictly greater than B
- Count of ways to split N into Triplets forming a Triangle
- Check if count of Alphabets and count of Numbers are equal in the given String
- How can we write main as a class in C++?
- Maximum sum of distinct numbers such that LCM of these numbers is N
- Python program maximum of three
- Number of Permutations such that no Three Terms forms Increasing Subsequence
- Program to find the smallest element among three elements
- Count of pairs with sum N from first N natural numbers
- Difference between sum of the squares of first n natural numbers and square of sum
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.