# Java program to find Nth pure number

Hello Friends, In this tutorial, we will look at what is Nth pure number then we will try to write code for Nth pure number in Java.

## Finding Nth pure number in Java

First of all, we define what is Nth pure number: So let’s learn what it is actually:

1. It should use the only digit 4 or 5.
2. It must have even number of digits.
3. It should be a palindrome.

Let’s take a look at some of the examples:

1. N=1 result would be “44”.
2. N=2 result would be “55”.
3. N=2 result would be “4444”.
4. N=2 result would be “4554”.
5. N=2 result would be “5445”.
6. N=2 result would be “5555”.

Looking at the pattern we can see New Pure number is a combination of what we get after appending “4” at the beginning and the last or appending “5” at the starting and the end. “4444” can be derived using “4” + “44” + “4” , “4554” is derived using “4”+”55“+”4”, “5445” is derived using “5”+”44“+”5” and “5555” using “5”+”55“+”5” where bolded numbers are previous pure numbers.

So, in each iteration i, we get new power(2, i) pure number using previously power(2, i-1) pure numbers by appending either “4” or “5” at both ends. We maintain a counter named as count that stops once we reach the Nth pure number.

For the implementation of the idea look at the following code:

```import java.util.*;
import java.io.*;

class nthpurenumber{

public static void main(String[] args)
{
int n = 5;    //Nth pure number to be found

String[] v= new String[n+1];
v[0]= "44" ;
v[1]= "55" ;

int count = 2;

int val=-1;
int i =0;
while(count < n )
{

i++;
int x = val+1;
val = x + (int)Math.pow(2,i)-1;

for(int k=x;k<=val;k++)
{

v[count]=("4"+v[k]+"4");
count++;
if(count >= n)
{
break;

}

}

for(int k=x;k<=val;k++)
{

v[count]=("5"+v[k]+"5");
count++;
if(count >= n)
{
break;

}

}
}

System.out.println(v[n-1]); // prints Nth pure number

}

}
```

When compiling the code using: javac nthpurenumber.java and then executing using java nthpurenumber we get the output:

`5445`

Thank You