Semiperfect Number | C ++ program to check if the number is semi - perfect or not ; code to find all the factors of the number excluding the number itself ; vector to store the factors ; note that this loop runs till sqrt ( n ) ; if the value of i is a factor ; condition to check the divisor is not the number itself ; return the vector ; Function to check if the number is semi - perfect or not ; find the divisors ; sorting the vector ; subset to check if no is semiperfect ; initialising 1 st column to true ; initializing 1 st row except zero position to 0 ; loop to find whether the number is semiperfect ; calculation to check if the number can be made by summation of divisors ; if not possible to make the number by any combination of divisors ; driver code to check if possible
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > factors ( int n ) { vector < int > v ; v . push_back ( 1 ) ; for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { v . push_back ( i ) ; if ( n / i != i ) { v . push_back ( n / i ) ; } } } return v ; } bool check ( int n ) { vector < int > v ; v = factors ( n ) ; sort ( v . begin ( ) , v . end ( ) ) ; int r = v . size ( ) ; bool subset [ r + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= r ; i ++ ) subset [ i ] [ 0 ] = true ; for ( int i = 1 ; i <= n ; i ++ ) subset [ 0 ] [ i ] = false ; for ( int i = 1 ; i <= r ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( j < v [ i - 1 ] ) subset [ i ] [ j ] = subset [ i - 1 ] [ j ] ; else { subset [ i ] [ j ] = subset [ i - 1 ] [ j ] || subset [ i - 1 ] [ j - v [ i - 1 ] ] ; } } } if ( ( subset [ r ] [ n ] ) == 0 ) return false ; else return true ; } int main ( ) { int n = 40 ; if ( check ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }