您可以通過或建立更大的數字:荷蘭國際集團一起多次打電話給蘭特()。
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define LIMIT (1000000)
static uint16_t highest_bit(uint64_t v) {
uint16_t out = 0;
while (v > 0) {
v >>= 1;
++out;
}
return out;
}
uint32_t myrand() {
static bool init = 0;
static uint16_t n;
static uint16_t shift;
if (!init) {
uint16_t randbits = highest_bit(RAND_MAX + (uint64_t)1L);
uint16_t outbits = highest_bit(LIMIT);
n = (outbits + randbits - 1)/randbits;
shift = randbits;
init = 1;
}
uint32_t out = 0;
for (uint16_t i=0; i<n; ++i) {
out |= rand() << (i*shift);
}
return out % LIMIT;
}
應當指出的是,這種方法會有偏差(即所有的數字將不會有相同的概率),它是絕對不是加密安全。如果你想要的話,你根本不應該使用rand()
。
下面就來測試所有的數字都至少可能得到一點主要功能:
int main() {
bool* seen = calloc(LIMIT, sizeof(bool));
if (!seen) {
fprintf(stderr, "failed to malloc 'seen' array\n");
return 1;
}
uint32_t nseen = 0;
uint32_t ntries = 0;
// this could take a long time -- you can use Ctrl-C to abort a command-line program
while (nseen < LIMIT) {
if ((ntries & 0xffff) == 0) {
printf("after %u tries, we've seen %u different numbers.\n", ntries, nseen);
}
++ntries;
uint32_t r = myrand();
if (!seen[r]) {
seen[r] = true;
++nseen;
}
}
printf("Found them all after %u tries!\n", ntries);
return 0;
}
'max'應該可能是'unsigned long',應該不是嗎? – Kundor