Open In App

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



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");

Following are the steps to solve this problem :

  1. Declare a vector data structure and a queue.
  2. Implement the function nPureNumbers(n) for generating first n pure numbers.
  3. Enqueue the first two elements ’44’ and ’55’ into the queue.
  4. Until the number of generated pure numbers is less than n then using while loop generate new pure numbers.
  5. Dequeue the first element from the queue and add it to the vector.
  6. Now concatenate ‘4’ or ‘5’ to create two purely new numbers and then enqueue them to the dequeued element.
  7. Lastly print first n pure numbers after sorting the generated pure number vector.

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;
}




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
 
class GFG {
  public static void nPureNumbers(int n) {
    Queue<String> q = new LinkedList<>();
    List<String> ans = new ArrayList<>();
 
    q.add("44");
    q.add("55");
    int total = 2;
 
    while (ans.size() < n) {
      String temp = q.poll();
      ans.add(temp);
 
      q.add("4" + temp + "4");
      q.add("5" + temp + "5");
    }
 
    Collections.sort(ans, (s, s2) -> {
      if (s.length() == s2.length()) {
        return s.compareTo(s2);
      } else {
        return s.length() - s2.length();
      }
    });
 
    for (String i : ans) {
      System.out.print(i + " ");
    }
  }
 
  public static void main(String[] args) {
    int n = 4;
    nPureNumbers(n);
  }
 
}
 
// This code is contributed by anskalyan3.




from queue import Queue
from typing import List
 
 
def nPureNumbers(n: int):
    q = Queue()
    ans = []
 
    q.put("44")
    q.put("55")
    total = 2
 
    while len(ans) < n:
        temp = q.get()
        ans.append(temp)
 
        q.put("4" + temp + "4")
        q.put("5" + temp + "5")
 
    ans.sort(key=lambda s: (len(s), s))
 
    print(*ans)
 
 
n = 4
nPureNumbers(n)




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program {
    public static void nPureNumbers(int n) {
        // Use a queue to store numbers to generate new ones
        Queue<string> q = new Queue<string>();
        // Use a list to store the generated numbers
        List<string> ans = new List<string>();
 
        // Add the initial numbers "44" and "55" to the queue
        q.Enqueue("44");
        q.Enqueue("55");
        int total = 2;
 
        // Generate new numbers until the list has n items
        while (ans.Count < n) {
            string temp = q.Dequeue();
            ans.Add(temp);
 
            // Add new numbers to the queue
            q.Enqueue("4" + temp + "4");
            q.Enqueue("5" + temp + "5");
        }
 
        // Sort the list of numbers by length and then lexicographically
        ans.Sort((s, s2) => {
            if (s.Length == s2.Length) {
                return s.CompareTo(s2);
            } else {
                return s.Length - s2.Length;
            }
        });
 
        // Print the list of numbers
        foreach (string i in ans) {
            Console.Write(i + " ");
        }
    }
 
    static void Main(string[] args) {
        int n = 4;
        nPureNumbers(n);
    }
}




// Define a function that takes an integer n as input
function nPureNumbers(n) {
 
  // Initialize a queue as an array with '44' and '55' as the first two elements
  let q = ['44', '55'];
   
  // Initialize an empty array to hold the n pure numbers
  let ans = [];
 
  // While the length of the ans array is less than n
  while (ans.length < n) {
   
    // Remove the first element from the queue and assign it to a temporary variable
    let temp = q.shift();
     
    // Add the temporary variable to the ans array
    ans.push(temp);
 
    // Add two new elements to the end of the queue:
    // 1. '4' + the temporary variable + '4'
    // 2. '5' + the temporary variable + '5'
    q.push('4' + temp + '4');
    q.push('5' + temp + '5');
  }
 
  // Sort the ans array in ascending order based on length, then lexicographically
  ans.sort((s, s2) => {
    if (s.length == s2.length) {
     
      // If two strings have the same length, compare them lexicographically
      return s.localeCompare(s2);
    } else {
     
      // Otherwise, sort them in ascending order based on length
      return s.length - s2.length;
    }
  });
 
  // Print the n pure numbers to the console, separated by spaces
  console.log(ans.join(' '));
}
 
// Call the nPureNumbers function with n = 4
let n = 4;
nPureNumbers(n);

Output:
44 55 4444 5445

Complexity Analysis :

Approach 2: The approach divides the even palindromic number into two equal parts, both of which mirror each other. The idea is to build the first part using the same approach that is used to build a binary counter by flipping every second bit; except, instead of flipping 0 and 1, we’re flipping 4 and 5. Later, we use the first part of the number and the palindromic property to create the final pure number.

44, 55, 4444, 4554... can be separated out into 
 4 | 4
 5 | 5
44 | 44
45 | 54
54 | 45
55 | 55

The numbers mimic the property of binary numbers of first ‘k’ bits where k = 1, 2, 3 and so on.

 0
 1
00
01
10
11

So, we start by flipping the last bit after every iteration, then moving to the (k-1) bit which is flipped after every 2 iterations and so on. The first time, it will be flipped n times and the next, it will be flipped n/2 times and so on. Since n is a sum of all possible numbers with k bits where k= 1, 2, 3…, our number will be a sum of 2 + 4 + 8 + …2k numbers. We consecutively divide n by 2 and stop if its value is equal to zero as there will be no further bits required to be added and also because, in the next iteration, the number will be flipped after twice the number of elements it took in the previous iteration. We can use a stack to store the values and then pop them out in sequential order, or by storing the data in a string and simply reversing it, which uses less space than a stack does. 

Following are the steps to solve this problem :

  1. Create a function naming ‘pure’ which accepts the integer input n and returns a string.
  2. Initialize an empty string p to hold the pure number.
  3. As long as n is more than 0, continue to append numbers to the string p using a while loop.
  4. Decrement n by 1 to equalize the value of n to parity with the corresponding flips.
  5. Append ‘4’ to the string p if n is even or append  ‘5’ in any other case.
  6. Now divide n by 2 to move to the next bit.
  7. Mark the string’s p length and reverse the string.
  8. To create the palindrome each character should be added  in the reversed string to the end of p.
  9. Use the ‘pure’ function to print the ith pure integer while looping over the values 1 through 10 in the main function.




#include <bits/stdc++.h>
using namespace std;
 
// Creating a function 'pure' that returns the pure number
// in the form of a string.
string pure(int n)
{
    // initializing string p where the number will be stored
    string p;
 
    // It keeps on adding numbers as long as n>0
    while (n > 0) {
 
        // To equalize the value of n to the corresponding flips
        n--;
        if (n % 2 == 0)
            p.append("4");
        else
            p.append("5");
 
        // Dividing n by 2 to move to the next bit
        n /= 2;
    }
 
    int len = p.length(); // Taking the length of the string
    reverse(p.begin(), p.end()); // Reversing the string
 
    for (int i = len - 1; i >= 0; i--) // Building the palindrome
        p += p[i];
 
    return p;
}
 
int main()
{
    for (int i = 1; i <= 10; i++)
        cout << pure(i) << " "; // Print Ith pure number
 
    return 0;
}




// Java code for above approach
import java.io.*;
 
class GFG {
 
// Creating a function 'pure' that returns the pure number
// in the form of a string.
 
static String pure(int n)
{
    // initializing string p where the number will be stored
    String p="";
 
    // It keeps on adding numbers as long as n>0
    while (n > 0) {
 
        // To equalize the value of n to the corresponding flips
        n--;
        if (n % 2 == 0)
            p+="4";
        else
            p+="5";
 
        // Dividing n by 2 to move to the next bit
        n /= 2;
    }
 
    int len = p.length(); // Taking the length of the string
    // Reversing the string
    StringBuffer P = new StringBuffer(p);
    P.reverse();
    p=P.toString();
 
    for (int i = len - 1; i >= 0; i--) // Building the palindrome
        p += p.charAt(i);
 
    return p;
}
 
public static void main (String[] args)
{
    for (int i = 1; i <= 10; i++)
        System.out.print(pure(i)+" "); // Print Ith pure number
 
}
}
 
// This code is contributed by Aman Kumar




# Python code for above approach
 
# Creating a function 'pure' that returns the pure number
# in the form of a string.
def pure(n):
    # initializing string p where the number will be stored
    p=""
     
    # It keeps on adding numbers as long as n>0
    while(n>0):
        # To equalize the value of n to the corresponding flips
        n-=1
        if(n%2==0):
            p+="4"
        else:
            p+="5"
             
        # Dividing n by 2 to move to the next bit
        n=n//2
     
    Len=len(p) # Taking the length of the string
    p[::-1] # Reversing the string
     
    # Building the palindrome
    for i in range(Len-1,-1,-1):
        p+=p[i]
     
    return p
 
for i in range(11):
    print(pure(i),end=" ") # Print Ith pure number
 
# This code is contributed by Pushpesh Raj.




// C# program for the above approach
 
using System;
 
class GFG
{
    // Creating a function 'pure' that returns the pure number
    // in the form of a string.
    static string pure(int n)
    {
        // initializing string p where the number will be stored
        string p = "";
 
        // It keeps on adding numbers as long as n>0
        while (n > 0)
        {
            // To equalize the value of n to the corresponding flips
            n--;
            if (n % 2 == 0)
                p += "4";
            else
                p += "5";
 
            // Dividing n by 2 to move to the next bit
            n /= 2;
        }
 
        int len = p.Length; // Taking the length of the string
        // Reversing the string
        char[] charArray = p.ToCharArray();
        Array.Reverse(charArray);
        p = new string(charArray);
 
        for (int i = len - 1; i >= 0; i--) // Building the palindrome
            p += p[i];
 
        return p;
    }
 
    public static void Main(string[] args)
    {
        for (int i = 1; i <= 10; i++)
            Console.Write(pure(i) + " "); // Print Ith pure number
    }
}
 
// This code is contributed by Prince Kumar




// Javascript equivalent
 
// Creating a function 'pure' that returns the pure number
// in the form of a string.
function pure(n) {
    // initializing string p where the number will be stored
    let p = "";
     
    // It keeps on adding numbers as long as n>0
    while (n > 0) {
        // To equalize the value of n to the corresponding flips
        n -= 1;
        if (n % 2 == 0) {
            p += "4";
        } else {
            p += "5";
        }
             
        // Dividing n by 2 to move to the next bit
        n = Math.floor(n / 2);
    }
     
    let len = p.length // Taking the length of the string
    p = p.split("").reverse().join(""); // Reversing the string
     
    // Building the palindrome
    for (let i = len - 1; i >= 0; i--) {
        p += p[i];
    }
     
    return p;
}
temp="";
for (let i = 0; i < 11; i++) {
    temp =temp + pure(i)+" "; // Print Ith pure number
} console.log(temp);

Output:
44 55 4444 4554 5445 5555 444444 445544 454454 455554

Complexity Analysis :


Article Tags :