Minimum number of power terms with sum equal to n
Last Updated :
12 Sep, 2023
Given two positive integer n and x. The task is to express n as sum of powers of x (xa1 + xa2 +…..+ xa3) such that the number of powers of x (xa1, xa2, ….., xa3) should be minimum. Print the minimum number of power of x used to make sum equal to n.
Examples:
Input : n = 5, x = 3
Output : 3
5 = 30 + 30 + 31.
We use only 3 power terms of x { 30, 30, 31}
Input : n = 13, x = 4
Output : 4
13 = 40 + 41 + 41 + 41.
We use only four power terms of x.
Input : n = 6, x = 1
Output : 6
If x = 1, then answer will be n only (n = 1 + 1 +…. n times).
The idea is to use Horner’s method. Any number n can be expressed as, n = x * a + b where 0 <= b <= x-1. Now since b is between 0 to x – 1, then b should be expressed as sum of x0 b times.
Further a can be decomposed in similar manner and so on.
Algorithm to solve this problem:
1. Initialize a variable ans to 0.
2. While n > 0
a) ans = ans + n % x
b) n = n/x
3. Return ans.
Below is the implementation of above idea :
C++
#include <bits/stdc++.h>
using namespace std;
int minPower( int n, int x)
{
if (x==1)
return n;
int ans = 0;
while (n > 0)
{
ans += (n%x);
n /= x;
}
return ans;
}
int main()
{
int n = 5, x = 3;
cout << minPower(n, x) << endl;
return 0;
}
|
Java
class GFG
{
static int minPower( int n, int x)
{
if (x== 1 )
return n;
int ans = 0 ;
while (n > 0 )
{
ans += (n % x);
n /= x;
}
return ans;
}
public static void main (String[] args)
{
int n = 5 , x = 3 ;
System.out.println(minPower(n, x));
}
}
|
Python3
def minPower(n,x):
if (x = = 1 ):
return n
ans = 0
while (n > 0 ):
ans + = (n % x)
n / / = x
return ans
n = 5
x = 3
print (minPower(n, x))
|
C#
using System;
class GFG
{
static int minPower( int n, int x)
{
if (x == 1)
return n;
int ans = 0;
while (n > 0)
{
ans += (n % x);
n /= x;
}
return ans;
}
public static void Main ()
{
int n = 5, x = 3;
Console.WriteLine(minPower(n, x));
}
}
|
PHP
<?php
function minPower( $n , $x )
{
if ( $x == 1)
return $n ;
$ans = 0;
while ( $n > 0)
{
$ans += ( $n % $x );
$n /= $x ;
}
return $ans ;
}
$n = 5; $x = 3;
echo (minPower( $n , $x ));
?>
|
Javascript
<script>
function minPower(n, x)
{
if (x==1)
return n;
let ans = 0;
while (n > 0)
{
ans += (n%x);
n = Math.floor(n / x);
}
return ans;
}
let n = 5, x = 3;
document.write(minPower(n, x) + "<br>" );
</script>
|
Output:
3
Time complexity: O(logxn)
Auxiliary space:O(1)
Share your thoughts in the comments
Please Login to comment...