Count perfect power of K in a range [ L , R ] | Python 3 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 INT_MAX ; loo3p 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
import sys NEW_LINE from math import pow , ceil , floor NEW_LINE import random NEW_LINE def nthRoot ( A , N ) : NEW_LINE INDENT xPre = ( random . randint ( 0 , 9 ) ) % 10 NEW_LINE eps = 1e-3 NEW_LINE delX = sys . maxsize NEW_LINE while ( delX > eps ) : NEW_LINE INDENT xK = ( ( N - 1.0 ) * xPre + A / pow ( xPre , N - 1 ) ) / N NEW_LINE delX = abs ( xK - xPre ) NEW_LINE xPre = xK NEW_LINE DEDENT return xK NEW_LINE DEDENT def countPowers ( a , b , k ) : NEW_LINE INDENT return ( floor ( nthRoot ( b , k ) ) - ceil ( nthRoot ( a , k ) ) + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 7 NEW_LINE b = 28 NEW_LINE k = 2 NEW_LINE print ( " Count ▁ of ▁ Powers ▁ is " , countPowers ( a , b , k ) ) NEW_LINE DEDENT