Write c program for random numbers generation. The basic function rand() can be used to generate a pseudo random integer value between 0 and RAND_MAX (0 and RAND_MAX included). The value of RAND_MAX is implementation dependent.

sample c program for random numbers generation

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {

   srand(time(NULL));
   int i;

   /* Print 5 random numbers from 0 to 200 */
   for( i = 0 ; i < 5 ; i++ ) {
      printf("%d\n", rand() % 200);
   }

    return 0;
}

Notes: The usage of rand() is not recommended for serious random number generation needs, like cryptography.

C program for random numbers generation based on xorshift

A better alternative of rand() function, is Xorshift, a class of pseudo-random number generators discovered by George Marsaglia. The Xorshift generator is a fastest non-cryptographic and secure random number generators.

c program for random numbers generation without using rand() function

The program is a simple modification of linear feedback shift registers (https://en.wikipedia.org/wiki/Linear-feedback_shift_register). This method uses the fact that when we allocate a memory, system returns the address of the memory address.

#include<stdio.h>

unsigned int lfsr = 0xACE1u;
unsigned int bit,temp=0;

unsigned int myrand(unsigned int max_range_from_0)
{
    int *p = malloc(sizeof(int));
    temp = temp^(int)p;
    bit  = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
    lfsr = ((bit<<15) | (lfsr>>1) | temp)%max_range_from_0;
    while(lfsr< 0){
        lfsr = lfsr + max_range_from_0 - 0;
    }
    return lfsr;
}

int main()
{
  int i=0;
  for(i=0; i <10; i++)
  {
     printf("%u\n",myrand(100));
  }
  return 0;
}

Note: The above program will generate random numbers from 0 to max_range_from_zero. if we want to generate random number between a range then we can modified the program as below.

#include<stdio.h>

unsigned int lfsr = 0xACE1u;
unsigned int bit,temp=0;
 
unsigned int myrand(unsigned int start_range,unsigned int max_range)
{
    int *p = malloc(sizeof(int));
    temp = temp^(int)p;
    bit  = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
    lfsr = ((bit<<15) | (lfsr>>1) | temp)%max_range;
    while(lfsr< start_range){
        lfsr = lfsr + max_range - start_range;
    }
    return lfsr;
}

int main()
{
  int i=0; 
  for(i=0; i <10; i++)
  {
     printf("%u\n",myrand(100,200));
  }
  return 0;
}

 

Ref:

https://en.wikipedia.org/wiki/Xorshift



Related Contents to follow