Solved

Generate Int64 random numbers

Posted on 2016-08-10
15
52 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
  • 6
  • 4
  • 3
  • +1
15 Comments
 
LVL 8

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 32

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 62

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
 

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 62

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 8

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

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 8

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 32

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 32

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 32

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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

707 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now