Solved

Generate Int64 random numbers

Posted on 2016-08-10
15
85 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 9

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 33

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
Industry Leaders: 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 9

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 9

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 33

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 33

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 33

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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
"Emulate" TAB key when press Enter Key 3 64
C#.net split string and then check appropriate checkboxlist 4 42
need to convert function to c# 5 40
Why use this lambda? 12 60
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

679 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