Find the first N pure numbers
Given an integer N, the task is to print first Nth pure numbers. A number is said to be pure if
- It has even number of digits.
- All the digits are either 4 or 5.
- And the number is a palindrome.
First few pure numbers are 44, 55, 4444, 4554, 5445, 5555, …
Examples:
Input: N = 4
Output: 44 55 4444 5445Input: N = 10
Output: 44 55 4444 4554 5445 5555 444444 454454 544445 554455
Approach: The idea is similar to the approach discussed here. At each step of the queue we can generate the next number by adding 4 and 5 on both of the sides i.e. the ending and the beginning of the previous number:
q.push("4" + temp + "4");
q.push("5" + temp + "5");
Proceeding in this way we can take care of palindromes and even length numbers
Below is the implementation of the above approach:
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to print the first n pure numbers void nPureNumbers(int n) { queue<string> q; vector<string> ans; // Push the starting two elements q.push("44"); q.push("55"); int total = 2; // While generated numbers are less than n while (ans.size() < n) { string temp = q.front(); q.pop(); ans.push_back(temp); q.push("4" + temp + "4"); q.push("5" + temp + "5"); } // Sorting strings based on their value sort(ans.begin(), ans.end(), [](auto s, auto s2) { if (s.size() == s2.size()) return s < s2; else return s.size() < s2.size(); }); // Print first n pure numbers for (auto i : ans) { cout << i << " "; } } // Driver code int main() { int n = 4; nPureNumbers(n); return 0; } |
44 55 4444 5445
Recommended Posts:
- Find original numbers from gcd() every pair
- Find the k largest numbers after deleting the given elements
- Find first k natural numbers missing in given array
- Rearrange numbers in an array such that no two adjacent numbers are same
- Sort all even numbers in ascending order and then sort all odd numbers in descending order
- Segregate even and odd numbers | Set 3
- Sort 3 numbers
- Stepping Numbers
- Kth number from the set of multiples of numbers A, B and C
- Sort the numbers according to their sum of digits
- Sort an array of large numbers
- Sort numbers stored on different machines
- Sort the numbers according to their product of digits
- No of pairs (a[j] >= a[i]) with k numbers in range (a[i], a[j]) that are divisible by x
- Sum of Semi-Prime Numbers less than or equal to N
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



