The Program in C++ Program to Create Hamming numbers within given range are given below:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> hamming_numbers(int n) {
vector<int> res = {1};
int i2 = 0, i3 = 0, i5 = 0;
for (int i = 1; i < n; i++) {
int next_2 = res[i2] * 2;
int next_3 = res[i3] * 3;
int next_5 = res[i5] * 5;
int next = min(next_2, min(next_3, next_5));
res.push_back(next);
if (next == next_2) i2++;
if (next == next_3) i3++;
if (next == next_5) i5++;
}
return res;
}
int main() {
int start, end;
cout << "Enter the start and end number of the range to find hamming numbers here : ";
cin >> start >> end;
vector<int> hamming = hamming_numbers(end);
cout << "Okay, the Hamming numbers in the given range interms of numbers are : " << endl;
for (auto num : hamming) {
if (num >= start) {
cout << num << " ";
}
}
cout << endl;
return 0;
}
Output:
Enter the start and end number of the range to find hamming numbers here : 1
10
Okay, the Hamming numbers in the given range interms of numbers are :
1 2 3 4 5 6 8 9 10 12
Pro-Tips💡
In this program, the user is prompted to enter the start and end of the range, and the program then calls the hamming_numbers
function to generate all the Hamming numbers up to the end of the range.
The function uses the logic of maintaining three pointers to track the next number that can be multiplied by 2, 3, or 5,
and then chooses the minimum of these three numbers to be the next Hamming number.
Finally, the program iterates over the list of Hamming numbers, and for each number, it checks if it is within the given range. If it is, it is printed to the screen.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.