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:
C++
#include <iostream>
using namespace std;
int minimumPowersOf3( int n)
{
int cnt = 0;
while (n > 0) {
cnt += n % 3;
n /= 3;
}
return cnt;
}
int main()
{
int n = 9;
int x = 5;
int mini = minimumPowersOf3(n);
int parity = abs (mini - x) % 2;
if (parity == 0 && x >= mini && x <= n) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
return 0;
}
|
Java
import java.util.Scanner;
public class GFG {
public static int minimumPowersOf3( int n)
{
int cnt = 0 ;
while (n > 0 ) {
cnt += n % 3 ;
n /= 3 ;
}
return cnt;
}
public static void main(String[] args)
{
int n = 9 ;
int x = 5 ;
int mini = minimumPowersOf3(n);
int parity = Math.abs(mini - x) % 2 ;
if (parity == 0 && x >= mini && x <= n) {
System.out.println( "YES" );
}
else {
System.out.println( "NO" );
}
}
}
|
Python3
def minimumPowersOf3(n):
cnt = 0
while n > 0 :
cnt + = n % 3
n / / = 3
return cnt
n = 9
x = 5
mini = minimumPowersOf3(n)
parity = abs (mini - x) % 2
if parity = = 0 and x > = mini and x < = n:
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
class Program
{
static int MinimumPowersOf3( int n)
{
int cnt = 0;
while (n > 0)
{
cnt += n % 3;
n /= 3;
}
return cnt;
}
static void Main( string [] args)
{
int n = 9;
int x = 5;
int mini = MinimumPowersOf3(n);
int parity = Math.Abs(mini - x) % 2;
if (parity == 0 && x >= mini && x <= n)
{
Console.WriteLine( "YES" );
}
else
{
Console.WriteLine( "NO" );
}
}
}
|
Javascript
function minimumPowersOf3(n) {
let cnt = 0;
while (n > 0) {
cnt += n % 3;
n = Math.floor(n / 3);
}
return cnt;
}
let n = 9;
let x = 5;
let mini = minimumPowersOf3(n);
let parity = Math.abs(mini - x) % 2;
if (parity === 0 && x >= mini && x <= n) {
console.log( "YES" );
} else {
console.log( "NO" );
}
|
Time Complexity: O(log3(N))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...