|
| 1 | +// C++ program to check if the number |
| 2 | +// is semi-perfect or not |
| 3 | +#include <bits/stdc++.h> |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +// code to find all the factors of |
| 7 | +// the number excluding the number itself |
| 8 | +vector<int> factors(int n) |
| 9 | +{ |
| 10 | + // vector to store the factors |
| 11 | + vector<int> v; |
| 12 | + v.push_back(1); |
| 13 | + |
| 14 | + // note that this loop runs till sqrt(n) |
| 15 | + for (int i = 2; i <= sqrt(n); i++) { |
| 16 | + |
| 17 | + // if the value of i is a factor |
| 18 | + if (n % i == 0) { |
| 19 | + v.push_back(i); |
| 20 | + |
| 21 | + // condition to check the |
| 22 | + // divisor is not the number itself |
| 23 | + if (n / i != i) { |
| 24 | + v.push_back(n / i); |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + // return the vector |
| 29 | + return v; |
| 30 | +} |
| 31 | + |
| 32 | +// Function to check if the |
| 33 | +// number is semi-perfect or not |
| 34 | +bool check(int n) |
| 35 | +{ |
| 36 | + vector<int> v; |
| 37 | + |
| 38 | + // find the divisors |
| 39 | + v = factors(n); |
| 40 | + |
| 41 | + // sorting the vector |
| 42 | + sort(v.begin(), v.end()); |
| 43 | + |
| 44 | + int r = v.size(); |
| 45 | + |
| 46 | + // subset to check if no is semiperfect |
| 47 | + bool subset[r + 1][n + 1]; |
| 48 | + |
| 49 | + // initialising 1st column to true |
| 50 | + for (int i = 0; i <= r; i++) |
| 51 | + subset[i][0] = true; |
| 52 | + |
| 53 | + // initializing 1st row except zero position to 0 |
| 54 | + for (int i = 1; i <= n; i++) |
| 55 | + subset[0][i] = false; |
| 56 | + |
| 57 | + // loop to find whether the number is semiperfect |
| 58 | + for (int i = 1; i <= r; i++) { |
| 59 | + for (int j = 1; j <= n; j++) { |
| 60 | + |
| 61 | + // calculation to check if the |
| 62 | + // number can be made by summation of divisors |
| 63 | + if (j < v[i - 1]) |
| 64 | + subset[i][j] = subset[i - 1][j]; |
| 65 | + else { |
| 66 | + subset[i][j] = subset[i - 1][j] || |
| 67 | + subset[i - 1][j - v[i - 1]]; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + // if not possible to make the |
| 73 | + // number by any combination of divisors |
| 74 | + if ((subset[r][n]) == 0) |
| 75 | + return false; |
| 76 | + else |
| 77 | + return true; |
| 78 | +} |
| 79 | + |
| 80 | +// driver code to check if possible |
| 81 | +int main() |
| 82 | +{ |
| 83 | + int n; |
| 84 | + cin >> n; |
| 85 | + for(int i =0 ; i <n ; i++){ |
| 86 | + if (check(i)) |
| 87 | + cout << i << " "; |
| 88 | + } |
| 89 | + return 0; |
| 90 | + |
| 91 | +} |
| 92 | + |
0 commit comments