finding multiples of a number in Python

后端 未结 7 1016
甜味超标
甜味超标 2021-02-07 10:48

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):
    prin         


        
相关标签:
7条回答
  • 2021-02-07 11:03
    def multiples(n,m,starting_from=1,increment_by=1):
        """
        # Where n is the number 10 and m is the number 2 from your example. 
        # In case you want to print the multiples starting from some other number other than 1 then you could use the starting_from parameter
        # In case you want to print every 2nd multiple or every 3rd multiple you could change the increment_by 
        """
        print [ n*x for x in range(starting_from,m+1,increment_by) ] 
    
    0 讨论(0)
  • 2021-02-07 11:04

    You can do:

    def mul_table(n,i=1):
        print(n*i)
        if i !=10:
            mul_table(n,i+1)
    mul_table(7)
    
    0 讨论(0)
  • 2021-02-07 11:12

    If this is what you are looking for -

    To find all the multiples between a given number and a limit

    def find_multiples(integer, limit):
        return list(range(integer,limit+1, integer))
    

    This should return -

    Test.assert_equals(find_multiples(5, 25), [5, 10, 15, 20, 25])
    
    0 讨论(0)
  • 2021-02-07 11:21

    For the first ten multiples of 5, say

    >>> [5*n for n in range(1,10+1)]
    [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
    
    0 讨论(0)
  • 2021-02-07 11:26

    Does this do what you want?

    print range(0, (m+1)*n, n)[1:]
    

    For m=5, n=20

    [20, 40, 60, 80, 100]
    

    Or better yet,

    >>> print range(n, (m+1)*n, n)
    [20, 40, 60, 80, 100] 
    

    For Python3+

    >>> print(list(range(n, (m+1)*n, n)))
    [20, 40, 60, 80, 100] 
    
    0 讨论(0)
  • 2021-02-07 11:26

    Based on mathematical concepts, I understand that:

    • all natural numbers that, divided by n, having 0 as remainder, are all multiples of n

    Therefore, the following calculation also applies as a solution (multiples between 1 and 100):

    >>> multiples_5 = [n for n in range(1, 101) if n % 5 == 0]
    >>> multiples_5
    [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
    

    For further reading:

    • https://www.mathsisfun.com/definitions/natural-number.html
    • https://www.mathwizz.com/arithmetic/help/help9.htm
    • https://www.calculatorsoup.com/calculators/math/multiples.php
    0 讨论(0)
提交回复
热议问题