|
| 1 | +""" |
| 2 | +A Hamming number is a positive integer of the form 2^i*3^j*5^k, for some |
| 3 | +non-negative integers i, j, and k. They are often referred to as regular numbers. |
| 4 | +The first 20 Hamming numbers are: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, and 36 |
| 5 | +""" |
| 6 | + |
| 7 | + |
| 8 | +def hamming(n_element: int) -> list: |
| 9 | + """ |
| 10 | + This function creates an ordered list of n length as requested, and afterwards |
| 11 | + returns the last value of the list. It must be given a positive integer. |
| 12 | + |
| 13 | + :param n_element: The number of elements on the list |
| 14 | + :return: The nth element of the list |
| 15 | + |
| 16 | + >>> hamming(5) |
| 17 | + [1, 2, 3, 4, 5] |
| 18 | + >>> hamming(10) |
| 19 | + [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] |
| 20 | + >>> hamming(15) |
| 21 | + [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] |
| 22 | + """ |
| 23 | + n_element = int(n_element) |
| 24 | + if n_element < 1: |
| 25 | + my_error = ValueError("a should be a positive number") |
| 26 | + raise my_error |
| 27 | + |
| 28 | + hamming_list = [1] |
| 29 | + i, j, k = (0, 0, 0) |
| 30 | + index = 1 |
| 31 | + while index < n_element: |
| 32 | + while hamming_list[i] * 2 <= hamming_list[-1]: |
| 33 | + i += 1 |
| 34 | + while hamming_list[j] * 3 <= hamming_list[-1]: |
| 35 | + j += 1 |
| 36 | + while hamming_list[k] * 5 <= hamming_list[-1]: |
| 37 | + k += 1 |
| 38 | + hamming_list.append( |
| 39 | + min(hamming_list[i] * 2, hamming_list[j] * 3, hamming_list[k] * 5) |
| 40 | + ) |
| 41 | + index += 1 |
| 42 | + return hamming_list |
| 43 | + |
| 44 | + |
| 45 | +if __name__ == "__main__": |
| 46 | + n = input("Enter the last number (nth term) of the Hamming Number Series: ") |
| 47 | + print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") |
| 48 | + hamming_numbers = hamming(int(n)) |
| 49 | + print("-----------------------------------------------------") |
| 50 | + print(f"The list with nth numbers is: {hamming_numbers}") |
| 51 | + print("-----------------------------------------------------") |
0 commit comments