Random numbers generation problem

1 次查看(过去 30 天)
Daniel
Daniel 2022-10-13
How to create randi([a,b],1,c) in which every number is not divided by 2,3,5,7,11 ? Or not neccecary in randi, it can be other function. I should create a row of random numbers in a specific interval that are not divided by 2,3,5,7,11.

回答(2 个)

David Goodmanson
David Goodmanson 2022-10-13
编辑:David Goodmanson 2022-10-13
Hi Daniel,
here is one way, basically the sieve of Eratosthenes.
nmax = 1000;
a = randi(nmax,1,1e6);
a(rem(a,2)== 0) = [];
a(rem(a,3)== 0) = [];
a(rem(a,5)== 0) = [];
a(rem(a,7)== 0) = [];
a(rem(a,11)== 0) = [];

John D'Errico
John D'Errico 2022-10-13
编辑:John D'Errico 2022-10-13
Just compute the set of all numbers in the interval you care about that are NOT divisible by those small primes. Technically, the numbers you care about are called rough numbers. Here, they would be called 13-rough, as the candidates you care about are divisible by no integer smaller than 13. (The smallest 13-rough number is 13., then 17 is next, etc. The smallest composite 13-rough number is 169=13^2.) But generating the list you want is simple. David shows how.
R = 100:1000;
R(mod(R,2) == 0 | mod(R,3) == 0 | mod(R,5) == 0 |mod(R,7) == 0 |mod(R,11) == 0) = [];
numel(R)
ans = 186
So there are 186 13-rough numbers between 100 and 1000. Remember that all primes greater than 11 are 13-rough.
Then sample randomly from that set. How would you sample randomly from a set of say 50 arbitrary integers? You use randi to generate random integers from 1 to 186 (in this case), then use them as indices into the set of interest.

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by