Skip to content

Commit

Permalink
2-B2 Sum を追加
Browse files Browse the repository at this point in the history
  • Loading branch information
Takeno-hito committed May 2, 2024
1 parent 750c478 commit a4f3c5b
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export default withMermaid({
items: [
{ text: '2-A1. Multiplication', link: '/text/chapter-2/practice/multiplication' },
{ text: '2-B1. 4bit', link: '/text/chapter-2/practice/4bit' },
{ text: '2-B2. Sum', link: '/text/chapter-2/practice/sum' },
],
},
]
Expand Down
1 change: 1 addition & 0 deletions docs/text/chapter-2/practice/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@

- [2-A1. Multiplication](multiplication)
- [2-B1. 4bit](4bit)
- [2-B2. Sum](sum)
39 changes: 39 additions & 0 deletions docs/text/chapter-2/practice/sum.md
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;
}
```

:::

0 comments on commit a4f3c5b

Please sign in to comment.