Given an integer N(1<=N<=10^9). The task is to represent N as a sum of the maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings. There can be multiple queries
Input : 12 Output : 3 Explanation : 12 can be written has 4 + 4 + 4 or 6 + 6 or 8 + 4 But, 4 + 4 + 4 has maximum number of summands. Input : 7 Output : -1
Approach : Note that minimal composite number is equal to 4. So it is quite logical that there will be a lot of 4 in a splitting of big numbers. Let’s write for small numbers (1<=M<=N) dpN be the number of composite summands in splitting of N.
Let’s find an answer for all numbers from 1 to 15. Several observations:
- Only 4, 6, 9 occurs in optimal splittings.
- It is not beneficial to use 6 or 9 more than once because 6 + 6 = 4 + 4 + 4, 9 + 9 = 6 + 6 + 6.
- 12, 13, 14, 15 have valid splittings.
Let’s prove that all numbers that are greater than 15 will have 4 in optimal splitting. Let’s guess that it is incorrect. If the minimal number in splitting is neither 4 nor 6 nor 9 then this number will have some non-trivial splitting by induction.
If this number either 6 or 9 and we will decrease query by this number then we will sooner or later get some small number (which is less or equal than 15). There is no splitting of small numbers or it contains 4 in splitting (and it contradicts with minimality of the first number) or it contains 6 and 9. So we have contradiction in all cases.
We can subtract 4 from any big query and our solution is correct.
If our query n is small number let’s print dpn. Else let’s find minimal number k such that n – 4·k is a small number. Then print k + dpn – 4·k.
Below is the implemetation of the above approach:
- Find the total number of composite factor for a given number
- Find a sequence of N prime numbers whose sum is a composite number
- Find maximum number that can be formed using digits of a given number
- Composite Number
- Find the maximum number of handshakes
- Find a positive number M such that gcd(N^M, N&M) is maximum
- Find prime number K in an array such that (A[i] % K) is maximum
- Find the maximum number of elements divisible by 3
- Find sum of a number and its maximum prime factor
- Find the Number of Maximum Product Quadruples
- Find the number in a range having maximum product of the digits
- Find a number that divides maximum array elements
- Find maximum power of a number that divides a factorial
- Find integers that divides maximum number of elements of the array
- Split n into maximum composite numbers
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.