How to Generate a Random Number with a Specific Amount of Digits

How to generate a random number with a specific amount of digits?

You can use either of random.randint or random.randrange. So to get a random 3-digit number:

from random import randint, randrange

randint(100, 999) # randint is inclusive at both ends
randrange(100, 1000) # randrange is exclusive at the stop

* Assuming you really meant three digits, rather than "up to three digits".


To use an arbitrary number of digits:

from random import randint

def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)

print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)

Output:

33
124
5127

Generating a random number with specific amount of digits and sum_of_digits (Python 3.8)

Simple solution

You can create a list of numbers which can be generated and then use random.choice() function to choose 1 element from list.

import random

n = int(input("Amount of digits: "))
x = int(input("Sum of digits: "))
numbers = [num for num in range(10 ** (n - 1), 10 ** n) if sum(map(int, str(num))) == x]
print(random.choice(numbers))

Fast solution

import random

t = []

def f(s, i):
r = sum(map(int, s))
if i == n:
if r == x:
t.append(s)
else:
for q in range(10) if len(s) else range(1, 10):
if r + q <= x:
f(s + str(q), i + 1)

n = int(input("Amount of digits: "))
x = int(input("Sum of digits: "))

f("", 0)
print(random.choice(t))

how to generate random numbers of specific digits?

You generate your randoms like this:

Random r = new Random();
int ran1 = r.nextInt(9)+1; // Will give values from 1-9
int ran2 = r.nextInt(90)+10; // Will give values from 10-99

You then create your string like this:
Opt 1 (Less recommended):

String s1 = String.valueOf(ran1);
String s2 = String.valueOf(ran2);
textSelectedFileName.setText(s1+s2);

Opt 2:

textSelectedFileName.setText(String.valueOf((ran1*100)+ran2));

How to generate a random number with the amount of digits, the user enters?

random.randint includes both bounders, so i think you mean random.randint(0, 9) in your example.

I suggest use math to solve your problem. n-digit number is number between 10**(n-1) and 10**n.

so it will look like this

digigts = int(digits)
num = random.randint(10**(digits - 1), 10**digits - 1)

How do you generate a random number that is 12 digits long in python?

welcome to the SO-community!

How about using random.randint between 10^12 and 10^13 - 1?

import random

print(random.randint(10**12, 10**13 - 1))
# randint is inclusive on both sides, so we need the - 1

# or

print(random.randrange(10**12, 10**13))
# randrange does not include the stop integer

Generate random numbers only with specific digits

Here is a solution using list-comprehension:

>>> random.sample([i for i in range(1,100_001) if all([int(x)%2==1 for x in str(i)])], 4)
[3115, 75359, 53159, 31771]

As pointed out in the comments below, the above code becomes more and more inefficient the larger the numbers get, due to all numbers being checked if each of them includes only odd-numbers. That includes numbers that are even.

IF we add another filter to first remove all even-numbers we reduce the amounts of comparisons that are being made by about a third.

Here is a quick comparison between the two:

import datetime
import random

def timer(var):
def wrapper(*args, **kwargs):
start = datetime.datetime.now()
result = var()
print(f"Elapsed time: {datetime.datetime.now()-start}")
return result
return wrapper

@timer
def allNumbers():
return random.sample([i for i in range(1, 1_000_001) if all([int(x) % 2 == 1 for x in str(i)])], 4)

@timer
def oddNumbers():
return random.sample([i for i in [x for x in range(1, 1_000_001) if x % 2 == 1] if all([int(x) % 2 == 1 for x in str(i)])], 4)

print("Calling allNumbers:")
print(allNumbers())
print("Calling oddNumbers:")
print(oddNumbers())

Output:

Calling allNumbers:
Elapsed time: 0:00:05.119071
[153539, 771197, 199379, 751557]
Calling oddNumbers:
Elapsed time: 0:00:02.978188
[951919, 1399, 199515, 791393]

How to Generate a random number of fixed length using JavaScript?

console.log(Math.floor(100000 + Math.random() * 900000));

Generate random number of certain amount of digits

Here is some pseudocode that should do what you want.

generateRandomNumber(20)
func generateRandomNumber(int numDigits){
var place = 1
var finalNumber = 0;
for(int i = 0; i < numDigits; i++){
place *= 10
var randomNumber = arc4random_uniform(10)
finalNumber += randomNumber * place
}
return finalNumber
}

Its pretty simple. You generate 20 random numbers, and multiply them by the respective tens, hundredths, thousands... place that they should be on. This way you will guarantee a number of the correct size, but will randomly generate the number that will be used in each place.

Update

As said in the comments you will most likely get an overflow exception with a number this long, so you'll have to be creative in how you'd like to store the number (String, ect...) but I merely wanted to show you a simple way to generate a number with a guaranteed digit length. Also, given the current code there is a small chance your leading number could be 0 so you should protect against that as well.



Related Topics



Leave a reply



Submit