Smallest number possible by repeatedly multiplying with K or 2 exactly N times starting from 1
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.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: N = 4, K = 3, X = 1
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
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:
Time Complexity: O(N)
Auxiliary Space: O(1)