Create a random number that is evenly divided by another in C #

I am making a quiz that will guide the user through basic arithmetic skills. The problem is that I do not want to be able to generate a split question that allows real numbers. I want all answers to have whole answers.

How can I randomly generate a number between p and q that evenly divides by n?

+4
source share
2 answers

The idea is to generate two integers a and n, and then return aand c = a * n. The defendant must guess that nand beware of dividing by zero !

Something like this will do:

public KeyValuePair<int, int> GenerateIntDivisibleNoPair(int p, int q) {
    if (p <= 0 || q <= 0 || q <= p)
        throw Exception(); //for simplification of idea
    Random rand = new Random();
    int a = rand.Next(p, q + 1); //cannot be zero! note: maxValue put as q + 1 to include q
    int n = rand.Next(p, q + 1); //cannot be zero! note: maxValue put as q + 1 to include q
    return new KeyValuePair<int, int>(a, a * n);
}

:

KeyValuePair<int, int> val = GenerateIntDivisibleNoPair(1, 101);
Console.WriteLine("What is " + val.Value.ToString() + " divide by " + val.Key.ToString() + "?");
+6

- :

public static Random Rnd { get; set; }

, , , , , Divisor:

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. .

+1

Source: https://habr.com/ru/post/1630019/


All Articles