Check if N can be represented as sum of distinct powers of 3 - GeeksforGeeks

16 Nov, 2021
Given a positive integer N, the task is to check whether the given number N can be represented as the sum of the distinct powers of 3. If found to be true, then print “Yes”. Otherwise, “No”.
Examples:
Input: N = 28Output: YesExplanation:The number N(= 28) can be represented (1 + 7) = (30 + 33), which is a perfect power 2.
Input: N = 6Output: No
Approach: The simplest approach to solve the given problem is to generate all possible permutations of all distinct powers of 3 and if there exists any such combination whose sum is a perfect power of 3. As 315 > 107 so there are only 16 distinct powers i.e., [0, 15].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to try all permutations// of distinct powersbool PermuteAndFind(vector<long> power, int idx,                    long SumSoFar, int target){    // Base Case    if (idx == power.size()) {         // If the distinct powers        // sum is obtained        if (SumSoFar == target)            return true;         // Otherwise        return false;    }     // If current element not selected    // in power[]    bool select        = PermuteAndFind(power, idx + 1, SumSoFar, target);     // If current element selected in    // power[]    bool notselect = PermuteAndFind(        power, idx + 1, SumSoFar + power[idx], target);     // Return 1 if any permutation    // found    return (select || notselect);} // Function to check the N can be// represented as the sum of the// distinct powers of 3void DistinctPowersOf3(int N){    // Stores the all distincts powers    // of three to [0, 15]    vector<long> power(16);    power[0] = 1;    for (int i = 1; i < 16; i++)        power[i] = 3 * power[i - 1];     // Function Call    bool found = PermuteAndFind(power, 0, 0L, N);     // print    if (found == true) {        cout << "Yes";    }    else {        cout << "No";    }} // Driven Codeint main(){    int N = 91;    DistinctPowersOf3(N);    return 0;}
// Java program for the above approachclass GFG{       // Function to try all permutations    // of distinct powers    public static boolean PermuteAndFind(int[] power, int idx,                                         int SumSoFar, int target)    {        // Base Case        if (idx == power.length)        {             // If the distinct powers            // sum is obtained            if (SumSoFar == target)                return true;             // Otherwise            return false;        }         // If current element not selected        // in power[]        boolean select = PermuteAndFind(power, idx + 1, SumSoFar, target);         // If current element selected in        // power[]        boolean notselect = PermuteAndFind(power, idx + 1, SumSoFar + power[idx], target);         // Return 1 if any permutation        // found        return (select || notselect);    }     // Function to check the N can be    // represented as the sum of the    // distinct powers of 3    public static void DistinctPowersOf3(int N)    {               // Stores the all distincts powers        // of three to [0, 15]        int[] power = new int[16];        power[0] = 1;        for (int i = 1; i < 16; i++)            power[i] = 3 * power[i - 1];         // Function Call        boolean found = PermuteAndFind(power, 0, 0, N);         // print        if (found == true) {            System.out.println("Yes");        } else {            System.out.println("No");        }    }     // Driven Code    public static void main(String args[]) {        int N = 91;        DistinctPowersOf3(N);    }} // This code is contributed by _saurabh_jaiswal.
# Python3 program for the above approach # Function to try all permutations# of distinct powersdef PermuteAndFind(power, idx, SumSoFar, target):         # Base Case    if (idx == len(power)):                 # If the distinct powers        # sum is obtained        if (SumSoFar == target):            return True                     # Otherwise        return False     # If current element not selected    # in power[]    select = PermuteAndFind(power, idx + 1,                            SumSoFar, target)     # If current element selected in    # power[]    notselect = PermuteAndFind(power, idx + 1,                                 SumSoFar + power[idx],                                 target)     # Return 1 if any permutation    # found    return(select or notselect) # Function to check the N can be# represented as the sum of the# distinct powers of 3def DistinctPowersOf3(N):         # Stores the all distincts powers    # of three to[0, 15]    power = [0 for x in range(16)]    power[0] = 1         for i in range(1, 16):        power[i] = 3 * power[i - 1]     # Function Call    found = PermuteAndFind(power, 0, 0, N)     # Print    if (found == True):        print("Yes")    else:        print("No") # Driver CodeN = 91 DistinctPowersOf3(N) # This code is contributed by amreshkumar3
// C# program for the above approachusing System; class GFG{     // Function to try all permutations    // of distinct powers    public static bool PermuteAndFind(int[] power, int idx,                                         int SumSoFar, int target)    {        // Base Case        if (idx == power.Length)        {             // If the distinct powers            // sum is obtained            if (SumSoFar == target)                return true;             // Otherwise            return false;        }         // If current element not selected        // in power[]        bool select = PermuteAndFind(power, idx + 1, SumSoFar, target);         // If current element selected in        // power[]        bool notselect = PermuteAndFind(power, idx + 1, SumSoFar + power[idx], target);         // Return 1 if any permutation        // found        return (select || notselect);    }     // Function to check the N can be    // represented as the sum of the    // distinct powers of 3    public static void DistinctPowersOf3(int N)    {               // Stores the all distincts powers        // of three to [0, 15]        int[] power = new int[16];        power[0] = 1;        for (int i = 1; i < 16; i++)            power[i] = 3 * power[i - 1];         // Function Call        bool found = PermuteAndFind(power, 0, 0, N);         // print        if (found == true) {            Console.Write("Yes");        } else {            Console.Write("No");        }    } // Driver Codepublic static void Main(){    int N = 91;    DistinctPowersOf3(N);}} // This code is contributed by avijitmondal1998.
<script>// Javascript program for the above approach // Function to try all permutations// of distinct powersfunction PermuteAndFind(power, idx, SumSoFar, target) {  // Base Case  if (idx == power.length) {    // If the distinct powers    // sum is obtained    if (SumSoFar == target) return true;     // Otherwise    return false;  }   // If current element not selected  // in power[]  let select = PermuteAndFind(power, idx + 1, SumSoFar, target);   // If current element selected in  // power[]  let notselect = PermuteAndFind(power, idx + 1, SumSoFar + power[idx], target);   // Return 1 if any permutation  // found  return select || notselect;} // Function to check the N can be// represented as the sum of the// distinct powers of 3function DistinctPowersOf3(N) {  // Stores the all distincts powers  // of three to [0, 15]  let power = new Array(16);  power[0] = 1;  for (let i = 1; i < 16; i++) power[i] = 3 * power[i - 1];   // Function Call  let found = PermuteAndFind(power, 0, 0, N);   // print  if (found == true) {    document.write("Yes");  } else {    document.write("No");  }} // Driven Code let N = 91;DistinctPowersOf3(N); </script>
Yes
Time Complexity: O(2N)Auxiliary Space: O(2N)
Another Approach: The above approach can also be optimized by observing the fact that N in ternary form (Base 3). Each digit is 3i, and the ternary number(N) is the sum of them.
To have distinct powers of 3, to sum up to N, in ternary form the ith digit can be either 0,1 or 2(In Binary, it is 0 and 1). Thus, there can be three cases for each digit at ith position: 
Digit can be 0 i.e. there is No 3i number in N.
Digit can be 1 i.e, there is One 3i number in N.
Digit cannot be 2 because then there are 2 of 3i, therefore, not distinct.
Follow the below steps to solve the problem: 
Iterate until N becomes 0 and perform the following steps:If the value of N%3 is 2, then print “No”.Otherwise, divide N by 3.
If the value of N%3 is 2, then print “No”.
Otherwise, divide N by 3.
After completing the above steps, if the value of N is 0 then print “Yes”. Otherwise, “No”.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether the given// N can be represented as the sum of// the distinct powers of 3void DistinctPowersOf3(int N){    // Iterate until N is non-zero    while (N > 0) {         // Termination Condition        if (N % 3 == 2) {            cout << "No";            return;        }         // Right shift ternary bits        // by 1 for the next digit        N /= 3;    }     // If N can be expressed as the    // sum of perfect powers of 3    cout << "Yes";} // Driver Codeint main(){    int N = 91;     DistinctPowersOf3(N);     return 0;}
// Java program for the above approachclass GFG{   // Function to check whether the given// N can be represented as the sum of// the distinct powers of 3public static void DistinctPowersOf3(int N){       // Iterate until N is non-zero    while (N > 0) {         // Termination Condition        if (N % 3 == 2) {            System.out.println("No");            return;        }         // Right shift ternary bits        // by 1 for the next digit        N /= 3;    }     // If N can be expressed as the    // sum of perfect powers of 3    System.out.println("Yes");} // Driver Codepublic static void main(String args[]){    int N = 91;     DistinctPowersOf3(N);}} // This code is contributed by _saurabh_jaiswal.
# Python3 program for the above approach # Function to check whether the given# N can be represented as the sum of# the distinct powers of 3def DistinctPowersOf3(N):       # Iterate until N is non-zero    while (N > 0):         # Termination Condition        if (N % 3 == 2):            cout << "No"            return         # Right shift ternary bits        # by 1 for the next digit        N //= 3     # If N can be expressed as the    # sum of perfect powers of 3    print ("Yes") # Driver Codeif __name__ == '__main__':    N = 91     DistinctPowersOf3(N) # This code is contributed by mohit kumar 29.
// C# program for the above approachusing System;class GFG{   // Function to check whether the given// N can be represented as the sum of// the distinct powers of 3static void DistinctPowersOf3(int N){       // Iterate until N is non-zero    while (N > 0) {         // Termination Condition        if (N % 3 == 2) {            Console.Write("No");            return;        }               // Right shift ternary bits        // by 1 for the next digit        N /= 3;    }       // If N can be expressed as the    // sum of perfect powers of 3    Console.Write("Yes");} // Driver Codepublic static void Main(){    int N = 91;    DistinctPowersOf3(N);}} // This code is contributed by Samim Hossain Mondal.
<script>// Javascript program for the above approach // Function to check whether the given// N can be represented as the sum of// the distinct powers of 3function DistinctPowersOf3(N){     // Iterate until N is non-zero    while (N > 0) {          // Termination Condition        if (N % 3 == 2)        {            document.write("No");            return;        }          // Right shift ternary bits        // by 1 for the next digit        N = Math.floor(N/ 3);    }      // If N can be expressed as the    // sum of perfect powers of 3    document.write("Yes");} // Driver Codelet N = 91;DistinctPowersOf3(N); // This code is contributed by patel2127</script>
Yes
Time Complexity: O(log3N)Auxiliary Space: O(1)
 
mohit kumar 29
amreshkumar3
patel2127
_saurabh_jaiswal
avijitmondal1998
samim2000
maths-power
Bit Magic
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Check whether K-th bit is set or not
Program to find parity
Write an Efficient Method to Check if a Number is Multiple of 3
Hamming code Implementation in C/C++
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7