A - Sigma Cubes Editorial by en_translator
If you are new to learning programming and do not know where to start, please try Problem A “Welcome to AtCoder” from practice contest. There you can find a sample code for each language.
Also, if you are not familiar with problems in programming contests, we recommend you to try some problems in “AtCoder Beginners Selection” (https://atcoder.jp/contests/abs).
This problem can be solved using a for
statement. Specifically, the answer can be found by the following procedure:
- Prepare a variable \(ans\) initialized with \(0\).
- For each \(i=1,2,\ldots,N\), add \((-1)^i\times i^3\) to \(ans\).
- Now \(ans\) stores the sought answer; print the value of \(ans\).
The problem can be solved by appropriately implementing the procedure above.
N = int(input())
ans = 0
for i in range(1, N + 1):
if i % 2 == 0:
ans += i * i * i
else:
ans -= i * i * i
print(ans)
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
int ans = 0;
for (int i = 1; i <= N; i++) {
if (i % 2 == 0) {
ans += i * i * i;
} else {
ans -= i * i * i;
}
}
cout << ans << endl;
}
Alternatively, you can use the formula \(\displaystyle \sum_{i=1}^N (-1)^i\times i^3=\frac{(-1)^N(4N^3+6N^2-1)+1}8\).
N = int(input())
print(((-1) ** N * (4 * N**3 + 6 * N**2 - 1) + 1) // 8)
posted:
last update: