Solved

Generate Int64 random numbers

Posted on 2016-08-10
15
106 Views
Last Modified: 2016-08-11
How can I generate a 16 digits Random numbers?

Using the .Net Random method can only generate 9 digits:

long n = new Random().Next(100000000, 999999999);


Any help would be greatly appreciated.


Thanks.
0
Comment
Question by:JimiJ13
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
  • 3
  • +1
15 Comments
 
LVL 10

Assisted Solution

by:Paweł
Paweł earned 125 total points
ID: 41750178
create a byte array of random values, then convert it to a int64

 Random rnd = new Random();
            var buffer = new byte[sizeof(Int64)];
            rnd.NextBytes(buffer);
            var num = BitConverter.ToInt64(buffer, 0);
            Console.WriteLine(num);
0
 
LVL 34

Accepted Solution

by:
sarabande earned 250 total points
ID: 41750241
or

Random rnd = new Random();
Int64 i64 = rnd.Next(1000000, 9999999);
i64 = (i64*1000000)+rnd.Next(0, 999999999);

Open in new window


Sara
0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 41750300
Hi  JimiJ13;

This is one way that Microsoft show how to do what you want.
From Microsoft Documentation:
The overloads of the Next method return 32-bit integers. However, in some cases, you might want to work with 64-bit integers. You can do this as follows:

1. Call the NextDouble method to retrieve a double-precision floating point value.
2. Multiply that value by Int64.MaxValue.

The following example uses this technique to generate 20 million random long integers and categorizes them in 10 equal groups. It then evaluates the distribution of the random numbers by counting the number in each group from 0 to Int64.MaxValue. As the output from the example shows, the numbers are distributed more or less equally through the range of a long integer.

const long ONE_TENTH = 922337203685477581;

Random rnd = new Random();
long number;
int[] count = new int[10];

// Generate 20 million long integers.
for (int ctr = 1; ctr <= 20000000; ctr++) {
 number = (long) (rnd.NextDouble() * Int64.MaxValue);
 // Categorize random numbers.
 count[(int) (number / ONE_TENTH)]++;
}
// Display breakdown by range.
Console.WriteLine("{0,28} {1,32}   {2,7}\n", "Range", "Count", "Pct.");
for (int ctr = 0; ctr <= 9; ctr++)
 Console.WriteLine("{0,25:N0}-{1,25:N0}  {2,8:N0}   {3,7:P2}", ctr * ONE_TENTH,
                    ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : Int64.MaxValue,
                    count[ctr], count[ctr]/20000000.0);
                              
The results of the above code
// The example displays output like the following:
//                           Range                            Count      Pct.
//    
//                            0-  922,337,203,685,477,580  1,996,148    9.98 %
//      922,337,203,685,477,581-1,844,674,407,370,955,161  2,000,293   10.00 %
//    1,844,674,407,370,955,162-2,767,011,611,056,432,742  2,000,094   10.00 %
//    2,767,011,611,056,432,743-3,689,348,814,741,910,323  2,000,159   10.00 %
//    3,689,348,814,741,910,324-4,611,686,018,427,387,904  1,999,552   10.00 %
//    4,611,686,018,427,387,905-5,534,023,222,112,865,485  1,998,248    9.99 %
//    5,534,023,222,112,865,486-6,456,360,425,798,343,066  2,000,696   10.00 %
//    6,456,360,425,798,343,067-7,378,697,629,483,820,647  2,001,637   10.01 %
//    7,378,697,629,483,820,648-8,301,034,833,169,298,228  2,002,870   10.01 %
//    8,301,034,833,169,298,229-9,223,372,036,854,775,807  2,000,303   10.00 %            
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:JimiJ13
ID: 41751400
@Paweł & @sarabande

Both of your suggestion works but how can I fix the result to 16 digits always?


Thanks.
0
 

Author Comment

by:JimiJ13
ID: 41751403
@Fernando Soto

Thanks for your suggestion. I want only to get one Random Number at a time.

Thanks.
0
 
LVL 63

Assisted Solution

by:Fernando Soto
Fernando Soto earned 125 total points
ID: 41751454
Hi JimiJ13;

How about something liken this.
const ulong minLong = 1000000000000000;
const ulong maxLong = 9999999999999999;

Random rnd = new Random();
ulong number;

do
{
    number = (ulong)(rnd.NextDouble() * maxLong);
}  while (!(number >= minLong && number <= maxLong));

Open in new window

0
 
LVL 10

Expert Comment

by:Paweł
ID: 41751487
Depends on how random you need your number to be, you could trim what is produced by either subtracting the appropriate value or by just pulling digits off, but I'm curious as to why you need a 16 digit number? Because if you are building unique keys you should use a GUID instead.
Something like var I'd = Guid.NewGuid();

It won't be a number, well sort of it'll be a hex value but very unique  almost certainly  unique, much more unique then any of the solutions provided
0
 

Author Comment

by:JimiJ13
ID: 41751493
@Fernando Soto

It works. However, is this not slower compare to other suggestion?


Thanks.
0
 

Author Comment

by:JimiJ13
ID: 41751529
@Paweł,

Your suggestion using GUID is really good if there is no existing BigInt data of about a million rows related to other tables and being used for 2-3 specific transactions.  We are doing now a new external transaction page and we need distinguish this by number of digits.

HTH,
0
 
LVL 10

Expert Comment

by:Paweł
ID: 41751564
you could try this

     static void Main(string[] args)
        {
            Random rnd = new Random();
            var buffer = new byte[(sizeof(Int64))];
            Console.WriteLine(Encoding.Default.GetString(buffer));
            rnd.NextBytes(buffer);
            var num = Math.Abs(BitConverter.ToInt64(buffer, 0));
            Console.WriteLine(num);
         
            Console.WriteLine((num % Math.Pow(10, 16)).ToString("000000000000000"));
        }

i'm really not sure which one is going to have better performance, maybe try both methods and capture some metrics
0
 
LVL 34

Expert Comment

by:sarabande
ID: 41751570
how can I fix the result to 16 digits always?

the Code i posted should guarantee 16 digits because the first of first seven digits is between 1 and 9 :

Int64 i64 = rnd.Next(1000000, 9999999); // this makes the number to have 7 digits

Open in new window


Sara
0
 

Author Comment

by:JimiJ13
ID: 41751608
@sarabande

Great! That gives me an idea to modify your solution to get what I want:

Random rnd = new Random();
            Int64 i64 = rnd.Next(10000000, 99999999);
            i64 = (i64 * 100000000) + rnd.Next(0, 999999999);
            this.NewNum.Text = Math.Abs(i64).ToString();

Thanks.
0
 
LVL 34

Expert Comment

by:sarabande
ID: 41751610
but very unique  almost certainly  unique, much more unique then any of the solutions provided
a GUID is a 128 bit number in the range of 0 to 2^128 what is about 3.4 x 10^38. that means the number has at least 37 decimal digits in the range from 0 to 9 each. if you reduce this to 16 digits you will use only the 10^21-th part of this pool what is still a huge number of more than 10 thousand trillion numbers, but any considerations about the uniqueness of the original guid number are out of question.

so if you don't make a methodical mistake, you could be sure that the uniqueness of your random 16-digits key "almost certainly" is guaranteed regardless of the method you were using. you will have to wait for some billion of years to get this to be falsified.

fyi: if you don't 'seed' the random object or 'seed' it with some random seed (say the seconds since 1/1/1970 divided by milliseconds since login), your numbers will always change with the time. if you take a fixed seed, the random series is always the same.

Sara
1
 

Author Closing Comment

by:JimiJ13
ID: 41751612
Great solution and invaluable suggestions.
0
 
LVL 34

Expert Comment

by:sarabande
ID: 41751620
the code i posted should guarantee 16 digits
note, if you finally need a string you also could pad numbers with less than 16 digits with leading zeros.

this method actually would use the full range from 0000000000000000 to 9999999999999999 while the other method starts from 1000000000000000.

Sara
0

Featured Post

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question