公式

A - Octave 解説 by en_translator


For beginners

Implementation approaches

There are many approaches to this problem.

Approach 1: loop

Repeat multiplying \(X\) by \(2\), \(Y\) times, and print the resulting \(X\).

Approach 2: shift operation or power operation

Most major programming languages has a way to obtain the value of \(2^Y\) fast.

For example, in C++ we can use the shift operation 1 << y; in Python we can use the power operation 2 ** y.

Approach 3: cover three cases

Since there are only three possible values for \(Y\), namely \(1\), \(2\), or \(3\), we can implement a conditional branch to perform the following operation:

  • If \(Y=1\), print the value of \(X \times 2\).
  • If \(Y=2\), print the value of \(X \times 4\).
  • If \(Y=3\), print the value of \(X \times 8\).

Sample code

Approach 1: loop

In C++, we can use the for statement to implement a loop.

#include <iostream>
using std::cin;
using std::cout;

int main (void) {
	int x, y;
	cin >> x >> y;

	int ans = x;
	for (int i = 0; i < y; i++) ans *= 2;

	cout << ans << "\n";
	
	return 0;
}

In Python, one can implement a loop by combining the for statement and range function.

x, y = map(int, input().split())

ans = x
for i in range(y):
	ans *= 2

print(ans)

Approach 2: shift operation and power operation

In C++, 1 << y represents \(2^Y\). This syntax works only for a non-negative-integer power of \(2\).

#include <iostream>
using std::cin;
using std::cout;

int main (void) {
	int x, y;
	cin >> x >> y;

	int ans = x * (1 << y);

	cout << ans << "\n";
	
	return 0;
}

In Python, 2 ** y represents \(2^Y\). This syntax accepts any operand values, not limited to powers of two.

x, y = map(int, input().split())

ans = x * (2 ** y)

print(ans)

Note that C++ and Python has pow and math.pow, respectively, but these functions returns a floating-point number, requiring an extra caution on precision errors and output format.

Approach 3: cover three cases

In C++, we can use the if-else statement to implement a conditional branch.

#include <iostream>
using std::cin;
using std::cout;
using std::cerr;

int main (void) {
	int x, y;
	cin >> x >> y;

	int ans;
	if (y == 1) {
		ans = x * 2;
	} else if (y == 2) {
		ans = x * 4;
	} else if (y == 3) {
		ans = x * 8;
	}

	cout << ans << "\n";
	
	return 0;
}

In Python, a conditional branch can be implemented using an if-elif statement.

x, y = map(int, input().split())

if y == 1:
	ans = x * 2
elif y == 2:
	ans = x * 4
elif y == 3:
	ans = x * 8

print(ans)

Since this problem guarantees that \(Y\) takes \(1\), \(2\), or \(3\), we can omit the case where all the three tests fail.

投稿日時:
最終更新: