Ask coding questions

← Back to all posts
RUNTIME IS LITERALLY MINUTES! GAH! c++ random numbers and functions
Highwayman (38)

I’m made a function that adds a bunch of modded random numbers together and puts them in an array, but my random numbers keep on being wildly big or negative numbers even though I’m modding them by six. It makes no sense! Could someone explain?

Answered by SPQR (414) [earned 5 cycles]
View Answer
SPQR (414)

I believe it's because you're calling rand() so many times. I'd recommend using <random> and mt19937. That's a much less hardware-intensive call to make.

Highwayman (38)

@SPQR thanks I’ll try that out :) what do you mean when you say it’s hardware intensive? How so?

SPQR (414)

@Highwayman It means that the rand() operation is complex and inefficient and thus requires a lot of processing power. Basically, It takes an extra step every time it's called, whereas if you use mt19937 you can do only one step with each pseudorandom number generated, thus running the program much faster.
An RNG is basically two components: a "seed" and a pseudorandum number generator. rand() generates a new seed each time it is called, as well as generating your "random" result. With mt19937 you can generate a seed once (usually at the beginning of the program) and use the same seed to generate multiple pseudorandom numbers. (The seed generation is the part that takes a lot of time.)

Highwayman (38)

@SPQR well then. Definitely going to keep that in mind 😂 thank you!