Smallest number possible by repeatedly multiplying with K or 2 exactly N times starting from 1
Last Updated :
16 Jul, 2021
Given two positive integers N and K, and an integer X ( initially 1 ), the task is to find the minimum value of X that can be obtained after performing one of the following operations N numbers of times:
- Increment the value of X by K.
- Double the current value of X.
Examples:
Input: N = 4, K = 3, X = 1
Output: 10
Explanation:
Following operations are performed:
Operation 1: Double the value of X from 1 to 2.
Operation 2: Double the value of X from 2 to 4.
Operation 3: Add the value K(= 3) to X modifies the value from 4 to 7.
Operation 4: Add the value K(= 3) to X modifies the value from 7 to 10.
After performing the above operations N(= 4) number of times, the value of X is 10, which is minimum among all possible combinations of operations performed.
Input: N = 7, K = 4, X = 1
Output: 24
Approach: The given problem can be solved by using the Greedy Approach. The idea is to perform one of the given operations repeatedly until performing the second operation locally maximize the value of X. Follow the steps below to solve the problem:
- Iterate over the range [1, N] and perform the following steps:
- If the value of X is less than K then update the value of X to X*2.
- Otherwise, increment the value of X by K.
- After completing the above steps, print the value of X as the minimum possible value of X.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minPossibleValue( int N, int K, int X)
{
for ( int i = 1; i <= N; i++) {
if (X <= K) {
X = X * 2;
}
else {
X = X + K;
}
}
return X;
}
int main()
{
int N = 7, K = 4, X = 1;
cout << minPossibleValue(N, K, X);
return 0;
}
|
Java
import java.io.*;
class GFG{
public static int minPossibleValue( int N, int K,
int X)
{
for ( int i = 1 ; i <= N; i++)
{
if (X <= K)
{
X = X * 2 ;
}
else
{
X = X + K;
}
}
return X;
}
public static void main(String[] args)
{
int N = 7 , K = 4 , X = 1 ;
System.out.println(minPossibleValue(N, K, X));
}
}
|
Python3
def minPossibleValue(N, K, X):
for i in range ( 1 , N + 1 ):
if (X < = K):
X = X * 2 ;
else :
X = X + K;
return X;
N = 7 ;
K = 4 ;
X = 1 ;
print (minPossibleValue(N, K, X));
|
C#
using System;
class GFG {
static int minPossibleValue( int N, int K, int X)
{
for ( int i = 1; i <= N; i++) {
if (X <= K) {
X = X * 2;
}
else {
X = X + K;
}
}
return X;
}
public static void Main()
{
int N = 7, K = 4, X = 1;
Console.WriteLine(minPossibleValue(N, K, X));
}
}
|
Javascript
<script>
function minPossibleValue(N, K, X)
{
for (let i = 1; i <= N; i++)
{
if (X <= K)
{
X = X * 2;
}
else
{
X = X + K;
}
}
return X;
}
let N = 7, K = 4, X = 1;
document.write(minPossibleValue(N, K, X));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...