Count perfect power of K in a range [ L , R ] | C ++ 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 ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; double nthRoot ( int A , int N ) { double xPre = rand ( ) % 10 ; double eps = 1e-3 ; double delX = INT_MAX ; double xK ; while ( delX > eps ) { xK = ( ( N - 1.0 ) * xPre + ( double ) A / pow ( xPre , N - 1 ) ) / ( double ) N ; delX = abs ( xK - xPre ) ; xPre = xK ; } return xK ; } int countPowers ( int a , int b , int k ) { return ( floor ( nthRoot ( b , k ) ) - ceil ( nthRoot ( a , k ) ) + 1 ) ; } int main ( ) { int a = 7 , b = 28 , k = 2 ; cout << " Count ▁ of ▁ Powers ▁ is ▁ " << countPowers ( a , b , k ) ; return 0 ; }