Long random numbers in C -
my problem simple (silly, maybe). need long random number using c language simple possible. researched through out internet , coudn't find me. thing find rand() function cannot handle numbers bigger 32,767.
here part of code, , long number should between 0 , 1,000,000:
#include <stdio.h> #include <time.h> #include <conio.h> #define max 999999 void main() { int i; printf("\n test random numbers."); printf("\n ------------------------------------\n\n"); srand(time(null)); for(i = 0; < 50; i++) { printf(" %li\n", rand() % max+1); } printf("\n ====================================\n"); getch(); }
you can build bigger numbers or:ing several calls rand().
#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; (uint16_t i=0; i<n; ++i) { out |= rand() << (i*shift); } return out % limit; }
it should noted method biased (i.e. numbers won't have same probability), , definitely not cryptographically secure. if want that, shouldn't using rand()
@ all.
here's little main function test numbers @ least possible get:
int main() { bool* seen = calloc(limit, sizeof(bool)); if (!seen) { fprintf(stderr, "failed malloc 'seen' array\n"); return 1; } uint32_t nseen = 0; uint32_t ntries = 0; // take long time -- can use ctrl-c abort 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 after %u tries!\n", ntries); return 0; }
Comments
Post a Comment