basics · beginner · ~15 min

Product of a range

Reuse the loop pattern for a product.

Challenge

Multiply every integer in an inclusive range together.

Task

Implement long product_range(int lo, int hi) that returns the product of all integers from lo to hi inclusive. If lo > hi the range is empty, so return 1 (the empty product). No main — the grader calls it.

Input

The inclusive bounds int lo and int hi.

Output

Returns the product of lo..hi, as a long (1 if lo > hi).

Example

product_range(1, 4)   ->   24    (1*2*3*4)
product_range(6, 6)   ->   6
product_range(5, 1)   ->   1     (empty product)

Edge cases

  • lo > hi returns 1 (the empty product).
  • A single-value range returns that value.

Input format

The inclusive bounds int lo and int hi.

Output format

The product of lo..hi as a long, or 1 if lo > hi.

Constraints

lo > hi returns 1 (the empty product).

Starter code

long product_range(int lo, int hi) {
    /* TODO */
    return 1;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.