easy +10 pts

Hexagonal Number

Determine if a given integer is a hexagonal number.

A hexagonal number is a figurate number that can be represented by a regular hexagon. The n-th hexagonal number (starting from n = 1) is given by the formula: H_n = n * (2n - 1). The sequence begins 1, 6, 15, 28, 45, ... Write a function `is_hexagonal(num)` that returns `True` if the given non-negative integer `num` is a hexagonal number, and `False` otherwise. Your function must handle inputs up to 1,000,000 efficiently. Use a loop that incrementally computes hexagonal numbers until the value exceeds `num`.

Constraints

0 <= num <= 1,000,000 Time complexity O(sqrt(num)) or better.

Example

>>> is_hexagonal(1)
True
>>> is_hexagonal(6)
True
>>> is_hexagonal(15)
True
>>> is_hexagonal(7)
False
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Compute hexagonal numbers in a loop: n = 1, 2, 3, ... until H_n > num.
The formula H_n = n * (2n - 1) grows quadratically, so the loop will run at most about sqrt(num) times.
If 0 is passed, return False because 0 is not a hexagonal number in this sequence.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.