Count perfect power of K in a range [ L , R ] | Java implementation to find the count of numbers those are powers of K in range L to R ; Function to find the Nth root of the number ; initially guessing a random number between 0 to 9 ; Smaller eps , denotes more accuracy ; Initializing difference between two roots by Integer . MAX_VALUE ; xK denotes current value of x ; loop until we reach desired accuracy ; calculating current value from previous value ; Function to count the perfect powers of K in range L to R ; Driver code
class GFG { static double nthRoot ( int A , int N ) { double xPre = Math . random ( ) * 10 % 10 ; double eps = 1e-3 ; double delX = Integer . MAX_VALUE ; double xK = 0 ; while ( delX > eps ) { xK = ( ( N - 1.0 ) * xPre + ( double ) A / Math . pow ( xPre , N - 1 ) ) / ( double ) N ; delX = Math . abs ( xK - xPre ) ; xPre = xK ; } return xK ; } static int countPowers ( int a , int b , int k ) { return ( int ) ( Math . floor ( nthRoot ( b , k ) ) - Math . ceil ( nthRoot ( a , k ) ) + 1 ) ; } public static void main ( String [ ] args ) { int a = 7 , b = 28 , k = 2 ; System . out . print ( " Count ▁ of ▁ Powers ▁ is ▁ " + countPowers ( a , b , k ) ) ; } }