Find the Nth Pure number | CPP program to find the Nth pure num ; Function to check if it is a power of 2 or not ; if a number belongs to 4 series it should lie between 2 ^ blocks - 1 to 2 ^ blocks + 2 ^ ( blocks - 1 ) - 1 ; Method to find pure number ; Iterate from 1 to N ; Check if number is power of two ; Distance to previous block numbers ; Distance to previous block numbers ; Driver Code ; Function call to find the Nth pure number
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOfTwo ( int N ) { double number = log ( N ) / log ( 2 ) ; int checker = int ( number ) ; return number - checker == 0 ; } bool isSeriesFour ( int N , int digits ) { int upperBound = int ( pow ( 2 , digits ) + pow ( 2 , digits - 1 ) - 1 ) ; int lowerBound = int ( pow ( 2 , digits ) - 1 ) ; return ( N >= lowerBound ) && ( N < upperBound ) ; } string getPureNumber ( int N ) { string numbers [ N + 1 ] ; numbers [ 0 ] = " " ; int blocks = 0 ; int displacement = 0 ; for ( int i = 1 ; i < N + 1 ; i ++ ) { if ( isPowerOfTwo ( i + 1 ) ) { blocks = blocks + 1 ; } if ( isSeriesFour ( i , blocks ) ) { displacement = int ( pow ( 2 , blocks - 1 ) ) ; numbers [ i ] = "4" + numbers [ i - displacement ] + "4" ; } else { displacement = int ( pow ( 2 , blocks ) ) ; numbers [ i ] = "5" + numbers [ i - displacement ] + "5" ; } } return numbers [ N ] ; } int main ( ) { int N = 5 ; string pure = getPureNumber ( N ) ; cout << pure << endl ; }