-7

I need help to random numbers without any std-function. How can I do that? I know that I can do it with the random-function like:

v2 = rand() % 36 + 1; 

which will randomize numbers between 1-35, but the rand() function belongs to the " (stdlib.h)" std.

Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160

2 Answers2

1

I found similar question on stackoverflow : How do I generate random numbers without rand() function?

I make little modifications for generating between 0-35 and final solution:

#include<stdio.h>
#include<time.h>
int main()
{
    int num = 36;
    time_t sec;
    sec=time(NULL);
        for(;;)
        {
            sec=sec%3600;
            if(num>=sec)
            {
            printf("%ld\n",sec);
            break;
            }
            sec=sec%num;
        }
    return 0;
}

Here we are using <time.h>for time instead of <stdlib.h> for rand() if we don't want 0 as answer then we can add

while(sec==0)
{
    sec=time(NULL); 
}

before this statement : sec=sec%3600;

Community
  • 1
  • 1
Kalpesh Dusane
  • 1,477
  • 3
  • 20
  • 27
0

You can use hardware random number generator:

#include <iostream>
#include "immintrin.h"

int main()
{
    unsigned int val;
    _rdrand32_step(&val);
    std::cout << val;
}
Ha.
  • 3,454
  • 21
  • 24