All challenges
Easy 0 solved 0% acceptance

Sum of Odd Numbers

Add every odd number up to a limit.

What you'll learn

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

Problem

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).

Constraints

0 ≤ n ≤ 1,000,000

Examples

Example 1
Input:
n = 7

Expected output:
expected = 16
Input:
long long n = 7;

Expected output:
long long expected = 16;
Input:
long n = 7;

Expected output:
long expected = 16;

Explanation

1 + 3 + 5 + 7 = 16.

Example 2
Input:
n = 0

Expected output:
expected = 0
Input:
long long n = 0;

Expected output:
long long expected = 0;
Input:
long n = 0;

Expected output:
long expected = 0;

Explanation

There are no odd numbers from 1 to 0, so the sum is 0.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

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

Hint 2

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

Hint 3

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

Expected complexity

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

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.