Practical Numbers | Java program to check if a number is Practical or not . ; 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
import java . util . * ; class GFG { static boolean isSubsetSum ( Vector < Integer > set , int n , int sum ) { boolean [ ] [ ] subset = new boolean [ n + 1 ] [ sum + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) subset [ i ] [ 0 ] = true ; for ( int i = 1 ; i <= sum ; i ++ ) subset [ 0 ] [ i ] = false ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= sum ; j ++ ) { if ( j < set . get ( i - 1 ) ) subset [ i ] [ j ] = subset [ i - 1 ] [ j ] ; if ( j >= set . get ( i - 1 ) ) subset [ i ] [ j ] = subset [ i - 1 ] [ j ] || subset [ i - 1 ] [ j - set . get ( i - 1 ) ] ; } } return subset [ n ] [ sum ] ; } static void storeDivisors ( int n , Vector < Integer > div ) { for ( int i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( i == ( n / i ) ) div . add ( i ) ; else { div . add ( i ) ; div . add ( n / i ) ; } } } } static boolean isPractical ( int N ) { Vector < Integer > div = new Vector < Integer > ( ) ; storeDivisors ( N , div ) ; for ( int i = 1 ; i < N ; i ++ ) { if ( ! isSubsetSum ( div , div . size ( ) , i ) ) return false ; } return true ; } public static void main ( String [ ] args ) { int N = 18 ; if ( isPractical ( N ) == true ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }