Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding multiples of a number in Python

Tags:

python

math

range

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.

like image 665
iKyriaki Avatar asked Jan 27 '13 23:01

iKyriaki


People also ask

How do you find multiples of a number in python?

We can use range() function in Python to store the multiples in a range. First we store the numbers till m multiples using range() function in an array, and then print the array with using (*a) which print the array without using loop. # of a number n without using loop. # (m * n)+1 incremented by n.

How do you find the multiples of 10 in python?

Use the modulo % operator to check if a number is a multiple of 10, e.g. if 100 % 10 == 0: . The modulo % operator returns the remainder from the division of the first number by the second. If the remainder is 0 , the number is a multiple of 10 .

How do you find the multiples of 3 and 5 in python?

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Note: If the number is a multiple of both 3 and 5, only count it once.

How do you check for multiples of 5 in python?

Use the modulus operator: if (num % 5 == 0) //the number is a multiple of 5.


1 Answers

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)
like image 103
Amber Avatar answered Oct 06 '22 22:10

Amber