Count of Perfect Numbers in given range for Q queries | C ++ 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
import java . util . * ; public class MyClass { static int MAX = 100005 ; static int isPerfect ( long N ) { long sum = 1 ; for ( long i = 2 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { if ( i * i != N ) sum = sum + i + N / i ; else sum = sum + i ; } } if ( sum == N && N != 1 ) return 1 ; return 0 ; } static void Query ( int arr [ ] [ ] , int N ) { int [ ] prefix = new int [ MAX + 1 ] ; Arrays . fill ( prefix , 0 ) ; for ( int i = 2 ; i <= MAX ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] + isPerfect ( i ) ; } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( prefix [ arr [ i ] [ 1 ] ] - prefix [ arr [ i ] [ 0 ] - 1 ] + " ▁ " ) ; } } public static void main ( String args [ ] ) { int [ ] [ ] arr = { { 1 , 1000 } , { 1000 , 2000 } , { 2000 , 3000 } } ; int N = arr . length ; Query ( arr , N ) ; } }