問題
Add all odd numbers from 1 up to and including n, using a loop.
Implement sum_of_odds(n).
Input
n: The upper limit.
Output
Return the sum of the odd numbers from 1 through n (0 if there are none).
制約
0 ≤ n ≤ 1,000,000
例
例 1
入力:
n = 7
期待される出力:
expected = 16
入力:
long long n = 7;
期待される出力:
long long expected = 16;
入力:
long n = 7;
期待される出力:
long expected = 16;
解説
1 + 3 + 5 + 7 = 16.
例 2
入力:
n = 0
期待される出力:
expected = 0
入力:
long long n = 0;
期待される出力:
long long expected = 0;
入力:
long n = 0;
期待される出力:
long expected = 0;
解説
There are no odd numbers from 1 to 0, so the sum is 0.
解き方のヒント
まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。
ヒント 1
奇数だけを足すので、1 から上へ見ながら偶数は飛ばす。
ヒント 2
条件に合う値だけを加えるループで十分。
ヒント 3
上限が 1 未満なら、合計は 0 のまま。
目安の計算量
時間 O(n)、追加メモリ O(1)
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。