简体   繁体   中英

Print multiples of a number less than a given max

Print multiples of n that are less than m.

def print_multiples(n, max):
  while n <= max:
    a = range(n, (n*max)+1,n)
    print(*a)

print_multiples(4, 18)

so this example would only print

4
8
12
16

and each answer is on a new line.

This code will do what you want. It divides the maximum number by the factor to get the maximum second factor ( // rounds down) and then adds one because it is range . Then it will iterate through each of the second factors and print out the multiples.

def print_multiples(n, m):
  for x in range(1, m//n + 1):
    print(x*n)

print_multiples(4, 18)

Also, you should avoid using max as a variable name because it is a keyword for the max() function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM