Skip to content

Instantly share code, notes, and snippets.

@morganwilde
Last active August 29, 2015 13:57
Show Gist options
  • Save morganwilde/9350559 to your computer and use it in GitHub Desktop.
Save morganwilde/9350559 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
unsigned intToBinaryInt(unsigned k, int *components, int counter) {
// k - current binary component
// components - collection of all the components
// counter - tracks how many components are there
if (k == 0) {
components[counter] = k;
return 0;
}
if (k == 1) {
components[counter] = k;
return 1;
}
components[counter] = (k % 2);
return (k % 2) + 10 * intToBinaryInt(k / 2, components, ++counter);
}
int multiply(int *components, int elements[], int elementCount) {
// components - marks each element from array to be multiplied by 1
// elements - the array that contains all the factors
// elementCount - how many
int i, j, product = 0;
for (i = 0; i < elementCount; i++) {
if (product)
product *= (components[i] * elements[i]) > 0 ? (components[i] * elements[i]) : 1;
else
product += components[i] * elements[i];
}
return product;
}
int main() {
// Storage
int elements = 4, // Numbers of factors
small[4] = {2, 5, 7, 8}, // Factors
big[100] = {0}, // Binary components
multiples[100] = {0}; // The array of all possible products
// Counters
int loops = pow(2, elements), // How many possible combinations
counter = 0; // The number of the current one
for (counter = 1; counter < loops; counter++) {
// Find a new configuration of multiples
intToBinaryInt(counter, big, 0);
// Include it into the collection
multiples[counter] = multiply(big, small, elements);
}
//
// Print the collection of multiples
//
printf("{");
for (counter = 1; counter < (loops-1); counter++) {
printf("%d, ", multiples[counter]);
}
printf("%d}\n", multiples[++counter]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment