Search code examples
python-3.xrecursioncounting

multiples of k below n (recursively)


I don't understand how to make the program as described.

I can do it in a non-generalized form, where I know what k is beforehand, but I don't know how to generalize it.

So if i know k is 7, then i can do it. But if i have to generalize it it doesn't work that way. What I need is a generalized version of what I have below

def multiples(k, n):
"""prints multiples of 7 below 500
"""

if k<=n:
    print(k)
    k+=7
    multiples(k, n)
multiples(7, 500)
    

Solution

  • You can add a start parameter to your function, which defaults to 0:

    def multiples(k, n, start=0):
        if (start <= n):
            print(start)
            start += k
            multiples(k, n, start)
    
    multiples(7, 500)
    

    Output:

    0
    7
    14
    ...
    497