Find the first N pure numbers
Last Updated :
24 Mar, 2023
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 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 :
- Declare a vector data structure and a queue.
- Implement the function nPureNumbers(n) for generating first n pure numbers.
- Enqueue the first two elements ’44’ and ’55’ into the queue.
- Until the number of generated pure numbers is less than n then using while loop generate new pure numbers.
- Dequeue the first element from the queue and add it to the vector.
- Now concatenate ‘4’ or ‘5’ to create two purely new numbers and then enqueue them to the dequeued element.
- 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:
CPP14
#include <bits/stdc++.h>
using namespace std;
void nPureNumbers( int n)
{
queue<string> q;
vector<string> ans;
q.push( "44" );
q.push( "55" );
int total = 2;
while (ans.size() < n) {
string temp = q.front();
q.pop();
ans.push_back(temp);
q.push( "4" + temp + "4" );
q.push( "5" + temp + "5" );
}
sort(ans.begin(), ans.end(), []( auto s, auto s2) {
if (s.size() == s2.size())
return s < s2;
else
return s.size() < s2.size();
});
for ( auto i : ans) {
cout << i << " " ;
}
}
int main()
{
int n = 4;
nPureNumbers(n);
return 0;
}
|
Java
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);
}
}
|
Python3
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)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
public static void nPureNumbers( int n) {
Queue< string > q = new Queue< string >();
List< string > ans = new List< string >();
q.Enqueue( "44" );
q.Enqueue( "55" );
int total = 2;
while (ans.Count < n) {
string temp = q.Dequeue();
ans.Add(temp);
q.Enqueue( "4" + temp + "4" );
q.Enqueue( "5" + temp + "5" );
}
ans.Sort((s, s2) => {
if (s.Length == s2.Length) {
return s.CompareTo(s2);
} else {
return s.Length - s2.Length;
}
});
foreach ( string i in ans) {
Console.Write(i + " " );
}
}
static void Main( string [] args) {
int n = 4;
nPureNumbers(n);
}
}
|
Javascript
function nPureNumbers(n) {
let q = [ '44' , '55' ];
let ans = [];
while (ans.length < n) {
let temp = q.shift();
ans.push(temp);
q.push( '4' + temp + '4' );
q.push( '5' + temp + '5' );
}
ans.sort((s, s2) => {
if (s.length == s2.length) {
return s.localeCompare(s2);
} else {
return s.length - s2.length;
}
});
console.log(ans.join( ' ' ));
}
let n = 4;
nPureNumbers(n);
|
Complexity Analysis :
- Time Complexity – O(n log n)
- Space Complexity – O(n)
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 :
- Create a function naming ‘pure’ which accepts the integer input n and returns a string.
- Initialize an empty string p to hold the pure number.
- As long as n is more than 0, continue to append numbers to the string p using a while loop.
- Decrement n by 1 to equalize the value of n to parity with the corresponding flips.
- Append ‘4’ to the string p if n is even or append ‘5’ in any other case.
- Now divide n by 2 to move to the next bit.
- Mark the string’s p length and reverse the string.
- To create the palindrome each character should be added in the reversed string to the end of p.
- Use the ‘pure’ function to print the ith pure integer while looping over the values 1 through 10 in the main function.
CPP
#include <bits/stdc++.h>
using namespace std;
string pure( int n)
{
string p;
while (n > 0) {
n--;
if (n % 2 == 0)
p.append( "4" );
else
p.append( "5" );
n /= 2;
}
int len = p.length();
reverse(p.begin(), p.end());
for ( int i = len - 1; i >= 0; i--)
p += p[i];
return p;
}
int main()
{
for ( int i = 1; i <= 10; i++)
cout << pure(i) << " " ;
return 0;
}
|
Java
import java.io.*;
class GFG {
static String pure( int n)
{
String p= "" ;
while (n > 0 ) {
n--;
if (n % 2 == 0 )
p+= "4" ;
else
p+= "5" ;
n /= 2 ;
}
int len = p.length();
StringBuffer P = new StringBuffer(p);
P.reverse();
p=P.toString();
for ( int i = len - 1 ; i >= 0 ; i--)
p += p.charAt(i);
return p;
}
public static void main (String[] args)
{
for ( int i = 1 ; i <= 10 ; i++)
System.out.print(pure(i)+ " " );
}
}
|
Python3
def pure(n):
p = ""
while (n> 0 ):
n - = 1
if (n % 2 = = 0 ):
p + = "4"
else :
p + = "5"
n = n / / 2
Len = len (p)
p[:: - 1 ]
for i in range ( Len - 1 , - 1 , - 1 ):
p + = p[i]
return p
for i in range ( 11 ):
print (pure(i),end = " " )
|
C#
using System;
class GFG
{
static string pure( int n)
{
string p = "" ;
while (n > 0)
{
n--;
if (n % 2 == 0)
p += "4" ;
else
p += "5" ;
n /= 2;
}
int len = p.Length;
char [] charArray = p.ToCharArray();
Array.Reverse(charArray);
p = new string (charArray);
for ( int i = len - 1; i >= 0; i--)
p += p[i];
return p;
}
public static void Main( string [] args)
{
for ( int i = 1; i <= 10; i++)
Console.Write(pure(i) + " " );
}
}
|
Javascript
function pure(n) {
let p = "" ;
while (n > 0) {
n -= 1;
if (n % 2 == 0) {
p += "4" ;
} else {
p += "5" ;
}
n = Math.floor(n / 2);
}
let len = p.length
p = p.split( "" ).reverse().join( "" );
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)+ " " ;
} console.log(temp);
|
Output:
44 55 4444 4554 5445 5555 444444 445544 454454 455554
Complexity Analysis :
- Time Complexity – O(n log n)
- Space complexity – O(n)
Share your thoughts in the comments
Please Login to comment...