Đề bài
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).
Ràng buộc
0 ≤ n ≤ 1,000,000
Ví dụ
Đầu vào:
n = 7
Kết quả mong đợi:
expected = 16
Đầu vào:
long long n = 7;
Kết quả mong đợi:
long long expected = 16;
Đầu vào:
long n = 7;
Kết quả mong đợi:
long expected = 16;
Giải thích
1 + 3 + 5 + 7 = 16.
Đầu vào:
n = 0
Kết quả mong đợi:
expected = 0
Đầu vào:
long long n = 0;
Kết quả mong đợi:
long long expected = 0;
Đầu vào:
long n = 0;
Kết quả mong đợi:
long expected = 0;
Giải thích
There are no odd numbers from 1 to 0, so the sum is 0.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Only odd numbers contribute, so skip the even ones while scanning upward.
Gợi ý 2
A loop that steps through the sequence and adds matching values is enough.
Gợi ý 3
If the upper limit is below 1, the total should stay zero.
Độ phức tạp mong đợi
O(n) time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.