Search code examples
pythonperformancemathrandom

How to generate two random numbers that are divisible by each other?


I wrote a simple math game that I can practice mental math. My concern is to make sure two numbers are always divisible by each other. I have tried the while loop to add 1 until it is divisible but it took too long:

import random
import operator

def random_problem():
  operators = {
    '+': operator.add,
    '-': operator.sub,
    'x': operator.mul,
    ':': operator.truediv
  };

  num1 = random.randint(1000,9999)
  num2 = random.randint(num1,9999)

  operation = random.choice(list(operators.keys()))

  if operation == ':':
    while num1 % num2 != 0:
      num2 += 1
  
  answer = (operators.get(operation)(num1, num2))
  print(f'What is {num1} {operation} {num2}')
  return answer

So any ideas to make this process faster?


Solution

  • A simple approach would be:

    1. Generate a random first number (n1)
    2. Generate a random multiplier (m)
    3. Use the product of the first number and the multiplier as the second number (n2 = n1 * m)