# 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

1. It has even number of digits.
2. All the digits are either 4 or 5.
3. 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 5445

Input: N = 10
Output: 44 55 4444 4554 5445 5555 444444 454454 544445 554455

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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 ` `using` `namespace` `std; ` ` `  `// Function to print the first n pure numbers ` `void` `nPureNumbers(``int` `n) ` `{ ` ` `  `    ``queue q; ` `    ``vector 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; ` `} `

Output:

```44 55 4444 5445
```

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

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.

Article Tags :
Practice Tags :

3

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.