Given a starting position as 0 and three integers X, Y, and K, the task is to find the position after K jumps,
the condition for the jumps are as follows:
- if the current jump is an even number then add X to the current position.
- else subtract Y to the current position.
Example :
Input : X = 5, Y = 2, K = 3 Output : 1 Explanation : For K = 1 as K is odd number 0-2 = -2 For K = 2 as K is even number -2+5 = 3 For K = 3 as K is odd number 3-2 = 1 Therefore the required answer is 1. Input : X = 100, Y = 1, K = 4 Output : 198
Approach :
Follow the below steps to solve the problem:
- Initialize a variable, say curPos = 0, to store the value of the current position.
- Initialize a variable, say evenK = X * (K/2), to store the position when K is an even number.
- Initialize a variable, say oddK = Y * (K/2 + K%2), to store the position when K is an odd number.
- Update curPos after K jumps as curPos = evenK – oddK.
- Finally, print the value of curPos.
Implementation :
// C++ implementation for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the current postion after
// K jumps as per the given condition
void currentPos(int X, int Y, int K) {
// Stores the current position
int curPos = 0;
// Stores the position for
// the even values of K
int evenK = X * (K / 2);
// Stores the position for
// the odd values of K
int oddK = Y * (K / 2 + K % 2);
// curPos after K jumps
curPos = evenK - oddK;
cout << curPos << endl;
}
// Driven
int main() {
int X = 5, Y = 2, K =3;
currentPos(X, Y, K);
return 0;
}
Time Complexity : O(1)
Space Complexity : O(1)