VOOZH about

URL: https://www.geeksforgeeks.org/dsa/represent-integer-as-sum-of-exactly-x-powers-of-three-the-powers-can-repeat/

⇱ Represent Integer as sum of exactly X Powers of three. The powers can repeat - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Represent Integer as sum of exactly X Powers of three. The powers can repeat

Last Updated : 26 Sep, 2023

Given two integers N and X (1<=N<=X<=1e9), the task is to find if it is possible to represent N as exactly X powers of 3.

Examples:

Input: N = 9, X = 5
Output: Yes
Explanation: 9 = 3^1 + 3^1 + 3^0 + 3^0 + 3^0

Input: N = 9, X = 4
Output: No

Approach: To solve the problem follow the below idea:

The idea is to use the ternary (base-3) representation of the integer N.

  • Convert N into its ternary representation.
  • Count the number of '2's (or '10's in ternary) in the ternary representation.
  • Check if the count of '2's is equal to X. If yes, then it is possible to represent N as exactly X powers of 3.

Below is the implementation for the above approach:


Output
YES

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

Comment
Article Tags: