Problema
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).
Vincoli
0 ≤ n ≤ 1,000,000
Esempi
Input:
n = 7
Output atteso:
expected = 16
Input:
long long n = 7;
Output atteso:
long long expected = 16;
Input:
long n = 7;
Output atteso:
long expected = 16;
Spiegazione
1 + 3 + 5 + 7 = 16.
Input:
n = 0
Output atteso:
expected = 0
Input:
long long n = 0;
Output atteso:
long long expected = 0;
Input:
long n = 0;
Output atteso:
long expected = 0;
Spiegazione
There are no odd numbers from 1 to 0, so the sum is 0.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
Only odd numbers contribute, so skip the even ones while scanning upward.
Suggerimento 2
A loop that steps through the sequence and adds matching values is enough.
Suggerimento 3
If the upper limit is below 1, the total should stay zero.
Complessità attesa
O(n) time, O(1) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.