// Arup Guha
// 4/16/2026
// Code to illustrate use of bitwise operators
// in subset sum function.
#include <stdio.h>

int subsetsum(int* values, int n, int target);

int main() {

    // Just a little test. Finds all possible targets.
    int vals[] = {17,27,1,93,16,49};
    for (int i=1; i<200; i++)
        if (subsetsum(vals,6,i))
            printf("%d ", i);
    return 0;
}

// Returns 1 iff there exists a subset of values[0..n-1]
// that adds up to target exactly.
int subsetsum(int* values, int n, int target) {

    // mask is an integer representing a subset of values.
    for (int mask=0; mask<(1<<n); mask++) {

        int total = 0;
        for (int j=0; j<n; j++)

            // Check if bit j is on in mask, if so add to running tally.
            if (mask&(1<<j))
                total += values[j];

        // We got a perfect match.
        if (total == target) return 1;
    }

    // None of the subsets worked.
    return 0;
}
