簡単 4件解決済み 正答率100.0%

Sum of Odd Numbers

Add every odd number up to a limit.

このチャレンジで学べること

  • Loop with a step of 2
  • Keep a running total
  • Include the limit when needed

問題

翻訳を表示

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

Only odd numbers contribute, so skip the even ones while scanning upward.

ヒント 2

A loop that steps through the sequence and adds matching values is enough.

ヒント 3

If the upper limit is below 1, the total should stay zero.

目安の計算量

O(n) time, O(1) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 KKKaneki Ken Python 928 ms - 4/5 コードを見る
2 RCRiccardo Corti Python 1,007 ms - 4/5 コードを見る
3 LMLaura Mahlow Python 1,014 ms - 4/5 コードを見る
4 HJhettory Jurash C++ 3,822 ms - 4/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が4件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。