![]() |
VOOZH | about |
Given a non-negative integer N, the task is to check if that integer can be represented as a summation of multiples of 3, 5, and 7, and print their respective values. If the task is not possible then print -1.
Examples:
Input: 10
Output: 1 0 1
Explanation: 10 can be represented as: (3 * 1) + (5 * 0) + (7 * 1) = 10. Other valid representation is (3 * 0) + (5 * 2) + (7 * 0)Input: 4
Output: -1
Explanation: 4 cannot be represented as a sum of multiples of 3, 5, and 7.
Naive Approach: The given problem can be solved by using three nested for loops, to iterate over multiples of 3, 5, and 7, and keeping track of whether there exists a combination with sum as N.
Below is the implementation of the above approach:
0 2 0
Time Complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach: The given problem can be solved by using maths.
Since every number can be represented in terms of multiple of 3, as 3x, 3x+1 or 3x+2. Using this fact, we can say that 5 can be represented in form 3x+2 and 7 can be represented in form 3x+1.
With the help of this observation, N can be represented in the 3 following ways:
Below is the implementation of the above approach:
101
Time Complexity: O(1)
Auxiliary Space: O(1)