Count numbers from a given range that can be expressed as sum of digits raised to the power of count of digits | javascript program for the above approach ; Function to check if a number N can be expressed as sum of its digits raised to the power of the count of digits ; Stores the number of digits ; Stores the resultant number ; Return true if both the numbers are same ; Function to precompute and store for all numbers whether they can be expressed ; Mark all the index which are plus perfect number ; If true , then update the value at this index ; Compute prefix sum of the array ; Function to count array elements that can be expressed as the sum of digits raised to the power of count of digits ; Precompute the results ; Traverse the queries ; Prvar the resultant count ; Driver Code ; function call
var R = 100005 ; var arr = Array ( R ) . fill ( 0 ) ; function canExpress ( N ) { var temp = N ; var n = 0 ; while ( N != 0 ) { N = parseInt ( N / 10 ) ; n ++ ; } N = temp ; var sum = 0 ; while ( N != 0 ) { sum += Math . pow ( N % 10 , n ) ; N = parseInt ( N / 10 ) ; } return ( sum == temp ) ; } function precompute ( ) { for ( var i = 1 ; i < R ; i ++ ) { if ( canExpress ( i ) ) { arr [ i ] = 1 ; } } for ( var i = 1 ; i < R ; i ++ ) { arr [ i ] += arr [ i - 1 ] ; } } function countNumbers ( queries , N ) { precompute ( ) ; for ( var i = 0 ; i < N ; i ++ ) { var L1 = queries [ i ] [ 0 ] ; var R1 = queries [ i ] [ 1 ] ; document . write ( ( arr [ R1 ] - arr [ L1 - 1 ] ) + " " ) ; } } var queries = [ [ 1 , 400 ] , [ 1 , 9 ] ] ; var N = queries . length ; countNumbers ( queries , N ) ;