Home > Back-end >  multiples of k below n (recursively)
multiples of k below n (recursively)

Time:09-27

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)
    

CodePudding user response:

You just need to keep track of the original value of k, which you wrote as 7 in your attempt.

I'd add a helper function, and do my recursion with that:

def multiples(k0, n):
    def _multiples(k):
        if k > n: return []
        return [k]   _multiples(k   k0)

    return _multiples(0)

print(multiples(7, 500))  # [0, 7, 14, 21, 28, ..., 497]

CodePudding user response:

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
  • Related