Given a number N (<1010), the task is to find the minimum number of factorials needed to represent N, as their sum. Also, print those factorials.
Input: N = 30 Output: 2 24, 6 Explanation: Factorials needed to represent 30: 24, 6 Input: N = 150 Output: 3 120, 24, 6 Explanation: Factorials needed to represent 150: 120 24 6
- In order to efficiently find the factorials which are needed to represent N as their sum, we can precompute the factorials till N (N < 1010) and store them in an array, for faster calculations.
- Then using Greedy Algorithm, we can take largest factorials from this array which can be added to represent N.
- Start from largest possible factorial and keep adding factorials while the remaining value is greater than 0.
- Below is the complete algorithm.
- Initialize result as empty
- find the largest factorial that is smaller than N
- Add found factorial to result. Subtract value of found factorial from N
- If N becomes 0, then print result. Else repeat steps 2 and 3 for new value of N
Below is the implementation of the above approach:
3 24 2 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 natural numbers whose factorials are divisible by x but not y
- Numbers whose factorials end with n zeros
- Check if a given number divides the sum of the factorials of its digits
- Find the unit place digit of sum of N factorials
- Find last two digits of sum of N factorials
- Find sum of factorials in an array
- Sum of factorials of Prime numbers in a Linked list
- Trailing number of 0s in product of two factorials
- Calculating Factorials using Stirling Approximation
- Queries for the product of first N factorials
- GCD of factorials of two numbers
- Print factorials of a range in right aligned format
- Product of first N factorials
- Maximum sum of two elements whose digit sum is equal
- Minimum number of squares whose sum equals to given number n
- Minimum number of squares whose sum equals to a given number N | Set-3
- Minimum number of squares whose sum equals to given number N | set 2
- Find a Number X whose sum with its digits is equal to N
- Count of numbers whose sum of increasing powers of digits is equal to the number itself
- Smallest number greater than or equal to X whose sum of digits is divisible by Y
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.