简体   繁体   中英

Generate random number with defined number of digits

I want to generate two different random numbers which has 15 digits. How can I do that

Thanks

Try this::

arc4random() is the standard Objective-C random number generator function. It'll give you a number between zero and... well, more than fifteen! You can generate a number between 0 and 15 (so, 0, 1, 2, ... 15) : A random number with 6 digits would be:

int number = arc4random_uniform(900000) + 100000;

it will give random numbers from 100000 to 899999.

Hope it Helps!!

Most random number generating functions such as arc4random produce only numbers in the range 0 .. 2^32-1 = 2147483647 . For a 15 digit decimal number, you can compute 3 numbers in the range 0 .. 10^5-1 and "concatenate" them:

uint64_t n1 = arc4random_uniform(100000); // 0 .. 99999
uint64_t n2 = arc4random_uniform(100000);
uint64_t n3 = arc4random_uniform(100000);

uint64_t number = ((n1 * 100000ULL) + n2) * 100000ULL + n3; // 0 .. 999999999999999

Or, if you need exactly 15 digits:

uint64_t n1 = 10000 + arc4random_uniform(90000); // 10000 .. 99999
uint64_t n2 = arc4random_uniform(100000); // 0 .. 99999
uint64_t n3 = arc4random_uniform(100000); // 0 .. 99999

uint64_t number = ((n1 * 100000ULL) + n2) * 100000ULL + n3;

using arc4random() functionality you can achieve to generate random numbers.

Here is the link that will give you pretty good idea about arc4random() .
hope this will help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM