Count the nodes in the given Tree whose weight is a Perfect Number | Javascript implementation to Count the nodes in the given tree whose weight is a Perfect Number ; Function that returns true if n is perfect ; Variable to store sum of divisors ; Find all divisors and add them ; Check if sum of divisors is equal to n , then n is a perfect number ; Function to perform dfs ; If weight of the current node is a perfect number ; Weights of the node ; Edges of the tree
var ans = 0 ; var graph = Array . from ( Array ( 100 ) , ( ) => Array ( ) ) ; var weight = Array . from ( Array ( 100 ) , ( ) => Array ( ) ) ; function isPerfect ( n ) { var sum = 1 ; for ( var 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 true ; return false ; } function dfs ( node , parent ) { if ( isPerfect ( weight [ node ] ) ) ans += 1 ; graph [ node ] . forEach ( to => { if ( to != parent ) dfs ( to , node ) ; } ) ; } weight [ 1 ] = 5 ; weight [ 2 ] = 10 ; weight [ 3 ] = 11 ; weight [ 4 ] = 8 ; weight [ 5 ] = 6 ; graph [ 1 ] . push ( 2 ) ; graph [ 2 ] . push ( 3 ) ; graph [ 2 ] . push ( 4 ) ; graph [ 1 ] . push ( 5 ) ; dfs ( 1 , 1 ) ; document . write ( ans ) ;