Given a stick of size N, find the number of ways in which it can be cut into K pieces such that length of every piece is greater than 0.
Input : N = 5 K = 2 Output : 4 Input : N = 15 K = 5 Output : 1001
Solving this question is equivalent to solving the mathematics equation x1 + x2 + ….. + xK = N
We can solve this by using the bars and stars method in Combinatorics, from which we obtain the fact that the number of positive integral solutions to this equation is (N – 1)C(K – 1), where NCK is N! / ((N – K) ! * (K!)), where ! stands for factorial.
In C++ and Java, for large values of factorials, there might be overflow errors. In that case we can introduce a large prime number such as 107 + 7 to mod the answer. We can calculate nCr % p by using Lucas Theorem.
However, python can handle large values without overflow.
Extend the above problem with 0 length pieces allowed. Hint : The number of solutions can similarly be found by writing each xi as yi – 1, and we get an equation y1 + y2 + ….. + yK = N + K. The number of solutions to this equation is (N + K – 1)C(K – 1)
This article is contributed by Deepak Srivatsav. 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.
- Print all possible strings of length k that can be formed from a set of n characters
- Factorial of a large number
- Number of ways to make mobile lock pattern
- Count ways to spell a number with repeated digits
- Paper Cut into Minimum Number of Squares
- Ways to represent a number as a sum of 1's and 2's
- Number of distinct permutation a String can have
- All possible strings of any length that can be formed from a given string
- Ways to sum to N using array elements with repetition allowed
- Count number of strings (made of R, G and B) using given combination
- Maximum number of 3-person teams formed from two groups
- Get the kth smallest number using the digits of the given number
- Count of Numbers in Range where the number does not contain more than K non zero digits
- Number of bitonic arrays of length n and consisting of elements from 1 to n
- Rearrangement of a number which is also divisible by it