Practical Numbers | Returns true if there is a subset of set [ ] with sun equal to given sum ; The value of subset [ i ] [ j ] will be true if there is a subset of set [ 0. . j - 1 ] with sum equal to i ; If sum is 0 , then answer is true ; If sum is not 0 and set is empty , then answer is false ; Fill the subset table in bottom up manner ; Function to store divisors of N in a vector ; Find all divisors which divides ' num ' ; if ' i ' is divisor of ' n ' ; if both divisors are same then store it once else store both divisors ; Returns true if num is Practical ; vector to store all divisors of N ; to check all numbers from 1 to < N ; Driver code
function isSubsetSum ( set , n , sum ) { var subset = Array . from ( Array ( n + 1 ) , ( ) => Array ( sum + 1 ) ) ; for ( var i = 0 ; i <= n ; i ++ ) subset [ i ] [ 0 ] = true ; for ( var i = 1 ; i <= sum ; i ++ ) subset [ 0 ] [ i ] = false ; for ( var i = 1 ; i <= n ; i ++ ) { for ( var j = 1 ; j <= sum ; j ++ ) { if ( j < set [ i - 1 ] ) subset [ i ] [ j ] = subset [ i - 1 ] [ j ] ; if ( j >= set [ i - 1 ] ) subset [ i ] [ j ] = subset [ i - 1 ] [ j ] || subset [ i - 1 ] [ j - set [ i - 1 ] ] ; } } return subset [ n ] [ sum ] ; } function storeDivisors ( n , div ) { for ( var i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( i == ( n / i ) ) div . push ( i ) ; else { div . push ( i ) ; div . push ( n / i ) ; } } } } function isPractical ( N ) { div = [ ] ; storeDivisors ( N , div ) ; for ( var i = 1 ; i < N ; i ++ ) { if ( ! isSubsetSum ( div , div . length , i ) ) return false ; } return true ; } var N = 18 ; isPractical ( N ) ? document . write ( " " ) : document . write ( " " ) ;