VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-number-n-can-be-represented-as-a-sum-of-multiples-of-3-5-and-7/

⇱ Check if a number N can be represented as a sum of multiples of 3, 5, and 7 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a number N can be represented as a sum of multiples of 3, 5, and 7

Last Updated : 23 Jul, 2025

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:


Output
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:

  • If N is of the form 3x, it can be represented as 3x.
  • If N is of the form 3x + 1,
    • If N > 7, then N can be represented as 3*(x - 2) + 7 as 7 is similar to 3*2 + 1.
    • Else if N <= 7, then it cannot be represented in the given form.
  • If N is of the form 3n + 2,
    • If N > 5, then N can be represented as 3x + 5 as 5 is similar to 3*1 + 2.
    • Else if N <= 5, then it cannot be represented in the given form.

Below is the implementation of the above approach:

 
 


Output: 
101

 


 

Time Complexity: O(1)
Auxiliary Space: O(1)


 

Comment
Article Tags:
Article Tags: