-4

So I have this

Random random1 = new Random();
int intrandom1 = random1.Next();

I want to put a long after the .Next. How do I do that? It only accepts ints.

Sean Bright
  • 118,630
  • 17
  • 138
  • 146

2 Answers2

3

First idea: A long as 64 bit integer, is the combination of 2 32 bit integers, so you can use:

((long)random1.Next() << 32)  | random1.Next()

Or perhaps

((long)random1.Next() <<< 32)  | random1.Next()

if you use java (?) and need a unsigned shift

edit: does not look like Java. Java has random1.nextLong() for that. Perhaps C#? I do not know that

BeniBela
  • 16,412
  • 4
  • 45
  • 52
  • 3
    Java already has [`Random.nextLong()`](http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextLong()) -which in facts works as you explain. +1 for the lateral thinking, anyway. – SJuan76 Dec 28 '12 at 18:16
  • Java doesn't have a Next() method and nextInt() it is signed so every second number would have all 1s for the top bits. – Peter Lawrey Dec 28 '12 at 18:20
  • Are you sure this will result in an even distribution along the number range? I'm inclined to think that it will bias the results a bit, but I'm not a good enough mathematician to prove it. – Servy Dec 28 '12 at 18:36
0

It can be generated arbitrary long number by using a simple linked list. Just imagine that every node from list can store a number random generated, and a function can be read that list like an unitary number. Using an algorithm like that you can obtain an arbitrary long random number.

Mihai8
  • 3,113
  • 1
  • 21
  • 31