Search code examples
pythonmathrange

finding multiples of a number in Python


I'm trying to write a code that lets me find the first few multiples of a number. This is one of my attempts:

def printMultiples(n, m):
for m in (n,m):
    print(n, end = ' ')

I figured out that, by putting for m in (n, m):, it would run through the loop for whatever number was m.

def printMultiples(n, m):
'takes n and m as integers and finds all first m multiples of n'
for m in (n,m):
    if n % 2 == 0:
        while n < 0:
            print(n)

After multiple searches, I was only able to find a sample code in java, so I tried to translate that into python, but I didn't get any results. I have a feeling I should be using the range() function somewhere in this, but I have no idea where.


Solution

  • If you're trying to find the first count multiples of m, something like this would work:

    def multiples(m, count):
        for i in range(count):
            print(i*m)
    

    Alternatively, you could do this with range:

    def multiples(m, count):
        for i in range(0,count*m,m):
            print(i)
    

    Note that both of these start the multiples at 0 - if you wanted to instead start at m, you'd need to offset it by that much:

    range(m,(count+1)*m,m)