Large random integers

Joined
Sep 20, 2022
Messages
269
Reaction score
40
I recently had to do this to test some large numbers for primeness.

Let x be any 100 digit integer.

How would you select a random number, from 0 to x-1, with each possible value equally likely?
I can do exact integer arithmetic, but my floating point is limited to 14 significant figures.
Code:
string y = "1"
loop 200 times
  append 1 random digit to y
end loop
y = x * y
truncate last 200 digits of y
return y - x
 
Joined
May 11, 2022
Messages
66
Reaction score
6
some thoughts:
i think you want y to simply equal ""
loop only 100 times
and convert to integer
but you still need to define how you generate 0 and 1 randomly and equally likely
 
Joined
Sep 20, 2022
Messages
269
Reaction score
40
I'm working in base 10.

For generating a random digit from 0 to 9, I just use the language's built-in random function.

Truncating could be a problem if y has leading zeros. That's what the initial 1 and final subtract is for.

If I used just 3 random digits, there's only 1000 random states, and if x were say 701440, there are many values from 0 to x-1 that will not be selected.

The more digits the better, I guessed that 200 would be good enough. Twice the length of x. There's always going to be a little bias if x doesn't divide the number of states exactly.
 
Joined
May 11, 2022
Messages
66
Reaction score
6
well if you're gonna use the built in function, why not simply do that at the start?
i assure you they're just as good.
 
Joined
Sep 20, 2022
Messages
269
Reaction score
40
The built-in random function produces a float, from 0 to 1. Normally I'd just multiply that by x and round off. But when x is huge, that isn't going to work.

I'm implementing the Rabin-Miller algorithm, not bouncing a ball around.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,333
Messages
2,571,383
Members
48,787
Latest member
hypercubes

Latest Threads

Top