Wednesday, December 30, 2009

What is the logic behind in generating random numbers between two limits?

I mean without using any predefined functions how to generate random numbers between two given limits in C?


I need a C program to solve it.What is the logic behind in generating random numbers between two limits?
one way to do this would be to grab some integer from the OS like the current date/time in millesconds. Once you have a large integer value you can use the math function of modular (usually MOD) in order to setup a way to get a value within a certain range. The modular function gives you the division remainder of a number when devided by a passed value. So, lets say you have a large number like 9999876 you can use 9999876 MOD(100) to find a number between 0 and 99 since any large, positive number divided my 100 will give you a remainder of 0 to 99. Change around the MOD(100) part to get different ranges.





hope this helpsWhat is the logic behind in generating random numbers between two limits?
What do you mean by predefined functions? If you are allowed to use standard libraries, if you #include stdlib.h you can use rand(). To get between two specific numbers do something like (MIN_VAL + rand() % (MAX_VAL- MIN_VAL)).





If you cant use external libraries you will need to find a pseudo random source. The rand() function mentioned above when seeded with srand() uses the current time in miliseconds to generate ';random'; numbers.

No comments:

Post a Comment