Count of Perfect Numbers in given range for Q queries | JavaScript program for the above approach ; Function to check whether a number is perfect Number ; Stores sum of divisors ; Itearate over the range [ 2 , sqrt ( N ) ] ; If sum of divisors is equal to N , then N is a perfect number ; Function to find count of perfect numbers in a given range ; Stores the count of perfect Numbers upto a every number less than MAX ; Iterate over the range [ 1 , MAX ] ; Traverse the array arr [ ] ; Print the count of perfect numbers in the range [ arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ] ; Driver Code
const MAX = 100005 ; function isPerfect ( N ) { let sum = 1 ; for ( let i = 2 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { if ( i * i != N ) sum = sum + i + Math . floor ( N / i ) ; else sum = sum + i ; } } if ( sum == N && N != 1 ) return true ; return false ; } function Query ( arr , N ) { let prefix = new Array ( MAX + 1 ) . fill ( 0 ) ; for ( let i = 2 ; i <= MAX ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] + isPerfect ( i ) ; } for ( let i = 0 ; i < N ; i ++ ) { document . write ( prefix [ arr [ i ] [ 1 ] ] - prefix [ arr [ i ] [ 0 ] - 1 ] + " " ) ; } } let arr = [ [ 1 , 1000 ] , [ 1000 , 2000 ] , [ 2000 , 3000 ] ] ; let N = arr . length ; Query ( arr , N ) ;