我会在某个地方声明一个具有全局访问权限的 Random:
public static Random Rnd { get; set; }
然后,当您想要一个数字除以另一个数字时,您会不断生成一个数字,直到您得到一个除以除数的数字:
if(Rnd == null)
{
Rnd = new Random();
}
int Min = p; //Can be any number
int Max = q; //Can be any number
if(Min > Max) //Assert that Min is lower than Max
{
int Temp = Max;
Max = Min;
Min = Temp;
}
int Divisor = n; //Can be any number
int NextRandom = Rnd.Next(Min, Max + 1); //Add 1 to Max, because Next always returns one less than the value of Max.
while(NextRandom % Divisor != 0)
{
NextRandom = Rnd.Next(Min, Max + 1); //Add 1 to Max, because Next always returns one less than the value of Max.
}
检查使用模数函数%。此函数为您提供整数除法的余数。
这意味着如果 NextRandom % Divisor 为 0,则 Divisor 均分到 NextRandom。
这可以变成这样的方法:
public static int GetRandomMultiple(int divisor, int min, int max)
{
if (Rnd == null)
{
Rnd = new Random();
}
if(min > max) //Assert that min is lower than max
{
int Temp = max;
max = min;
min = Temp;
}
int NextRandom = Rnd.Next(min, max + 1); //Add 1 to Max, because Next always returns one less than the value of Max.
while (NextRandom % divisor != 0)
{
NextRandom = Rnd.Next(min, max + 1); //Add 1 to Max, because Next always returns one less than the value of Max.
}
return NextRandom;
}
然后你可以用你提到的变量来调用它:
int Number = GetRandomMultiple(n, p, q);
注意:由于“下一步”方法,我将 Max 的值加一。我认为这是.Net中的一个错误。 Max 的值永远不会返回,只有 Min..Max - 1。加一可以弥补这一点。