如何生成一组数字

时间:2015-07-01 14:10:14

标签: c math

我必须生成满足等式Z的前100个整数的集合i = 2^a * 3^b,其中ab是整数。

Z = {1, 2, 3, 4, 6, 8, 9, 12, ...}

我可以使用什么算法?我需要在C中实现它。

3 个答案:

答案 0 :(得分:2)

在C

#include <stdio.h>
#include <math.h>
#include <stdint.h>
typedef unsigned long long int ull;

ull cmp(const void * a, const void * b) { return *(ull *)a  - *(ull *)b; } 

int main() {
    int i = 0, a, b;
    int A = 17, 
        B = 16;
    int MAX = A * B;
    ull z[MAX];
    for (b = 0; b < B; ++b) {
        for (a = 0; a < A; ++a) {
            if (i >= MAX) break;
            z[i++] = pow(2, a) * pow(3, b);
        }
    }
    qsort(z, MAX, sizeof(ull), cmp);
    printf("{ ");
    for (i = 0; i < 100; ++i)
        printf("%lld%c ", z[i], i < 99 ? ',' : 0);
    printf("}");
    return 0;
}

输出

  

{1,2,3,4,6,8,9,12,16,18,24,27,32,36,48,54,64,72,81,96,108,128,144, 162,192,216,243,256,288,324,384,432,486,512,576,648,729,768,864,972,1024,1152,1296,1458,1536,1728,1944,2048, 2187,2304,292,2916,3072,356,3888,496,1374,4608,5184,5832,6144,6561,6912,7776,8192,8748,9216,10368,11664,12288,13122,13824,15552, 16384,17549,18432,19683,20736,23328,24576,26244,27648,31104,32768,34992,36864,39366,41472,46656,49152,52488,5529,69049,62208,65536,69984,73728,78732, 82944,93312}

编辑:现在提供正确的输出而不会溢出(请参阅http://ideone.com/Rpbqms

答案 1 :(得分:2)

太暴力了......

让我提出一个O(n*lg n)时间O(n)空间算法来实现这些目标。

我不会提供任何真正的代码,而是一个自我发明的伪代码。

这个想法是使用min-heap来维护排序:

func first-n-of-that(limit)
    heap = min-heap()
    heap.insert 1
    results = []
    while results.length < limit
        to-add = heap.pop
        results.add to-add
        heap.insert 2 * to-add
        heap.insert 3 * to-add
    return results

通过演绎证明正确性。

答案 2 :(得分:1)

Python中的暴力(我知道需要C代码):

sorted(2**a*3**b for a in range(100) for b in range(100))[:100]

结果是......