- 将集合编码为素数的乘积
- 计算公共子集作为结果数字的 GCD
- 分解生成的 GCD 以显示常见项目。
- 这当然受到项目数量和集合大小的限制(否则素数的乘积可能会溢出)
#include <stdio.h>
#include <string.h>
unsigned primes [] = { 2,3,5,7,11,13,17, 19, 23, 29,31,37,41,43,47};
unsigned value(unsigned array[], unsigned count);
unsigned gcd(unsigned a, unsigned b);
unsigned factorise(unsigned result[], unsigned val);
unsigned value(unsigned array[], unsigned count)
{
unsigned val, idx;
val = 1;
for (idx = 0; idx < count; idx++) {
val *= primes [ array[idx]];
}
return val;
}
unsigned gcd(unsigned a, unsigned b)
{
if (b > a) return gcd (b, a);
if (b <= 1) return a;
if (b == a) return a;
return gcd (b, a-b);
}
unsigned factorise(unsigned result[], unsigned val)
{
unsigned idx, count;
for (count=idx=0; val > 1; ) {
if ( val % primes[idx] ) idx++;
else {
result[count++] = idx;
val /= primes[idx];
}
}
return count;
}
int main(void)
{
unsigned one[] = {4, 3, 8, 12, 5, 4, 4, 4};
unsigned two[] = {5, 4, 12, 1, 1, 4, 1, 1};
unsigned three[] = {2, 11, 4, 8, 4, 5, 2, 8};
unsigned result[12] , count, idx;;
unsigned val1, val2,val3
, gcd12 , gcd23 , gcd13, gcd123;
val1 = value(one, 8);
val2 = value(two, 8);
val3 = value(three, 8);
gcd12 = gcd(val1,val2);
gcd23 = gcd(val2,val3);
gcd13 = gcd(val1,val3);
gcd123 = gcd(gcd12,gcd23);
fprintf(stdout, "Val1=%u, Val2=%u Val3=%u gcd= [%u %u %u]: %u\n"
, val1, val2, val3
, gcd12 , gcd23 , gcd13, gcd123);
count = factorise( result, gcd123);
for (idx=0; idx < count; idx++) {
fprintf(stdout, "%c %u", idx? ',' : '{', result[idx] );
}
fprintf(stdout, "}\n" );
return 0;
}
这是基于我在这里的回答。