-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
750c478
commit a4f3c5b
Showing
3 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,3 +2,4 @@ | |
|
||
- [2-A1. Multiplication](multiplication) | ||
- [2-B1. 4bit](4bit) | ||
- [2-B2. Sum](sum) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
# 2-A2. Sum of n | ||
|
||
cin で自然数 $n$ を受け取って、$1$ から $n$ までの和を出力するプログラムを作成してください。 | ||
|
||
例えば `10` を受け取ったとき、 1+2+3+4+5+6+7+8+9+10 を計算して `55` を出力できれば OK です。 | ||
|
||
::: spoiler Hint 1 | ||
今までの知識で解けるはず。手で計算する時、わざわざ足していますか? | ||
::: | ||
|
||
::: spoiler Hint 2 | ||
総和を求める公式は $\dfrac{1}{2} n (n+1)$ でした。 | ||
::: | ||
|
||
::: spoiler Hint 3 (なぜか計算が合わない人) | ||
プログラムにおいては、計算は左から順番に行われ、途中計算は必ず int 型(=整数)に切り捨てられます。 | ||
|
||
つまり、最初に `1/2` と書くとそこで 0 になってしまいます。 | ||
|
||
計算の順序を工夫する必要がありそうです。 | ||
::: | ||
|
||
::: spoiler Answer | ||
|
||
```cpp | ||
#include <iostream> | ||
using namespace std; | ||
|
||
int main() { | ||
int n = 10; | ||
cin >> n; | ||
|
||
int ans = n*(n+1)/2; | ||
|
||
cout << ans << endl; | ||
} | ||
``` | ||
|
||
::: |