user12859311
user12859311

Reputation:

Counting multiples of a factor in Python with return

What do I need to write after the return so that this function will count the multiples of a given factor?

def count_multiples(factor, maximum):

    return #number of multiples of 'factor' up to 'maximum'

count_multiples(3, 20) #for example

The function takes two integers as parameter:

The function needs to return an integer value, which is the total number of multiples of factor greater than 0 and less than or equal to maximum.

In this case, the outcome needs to be: 6, because the numbers 3, 6, 9, 12, 15 and 18 are the multiples of 3 within the range 0 and 20.

Thank you.

Upvotes: 0

Views: 1811

Answers (3)

azro
azro

Reputation: 54148

  1. The pythonic way may be

    def count_multiples(factor, maximum):
        return len(range(factor, maximum + 1, factor))
    
  2. but the arithmetic is the int division of the max by the factor :

    def count_multiples(factor, maximum):
        return maximum // factor
    

# To get
if __name__ == '__main__':
    print(count_multiples(3, 20))  # 6
    print(count_multiples(3, 21))  # 7

Upvotes: 1

Marses
Marses

Reputation: 1572

return maximum // factor

Should give you what you want no? As in this will return the division without remainder, which is equal to the largest number you can multiply factor by such that the result is less than or equal to maximum. It will also return the right type (int).

Actually some of the comments already answered this before me.

Upvotes: 1

user12859556
user12859556

Reputation:

def count_multiples(factor, maximum):
    return int(maximum/factor)
count_multiples(3,20) # would give you '6' as output

Upvotes: 1

Related Questions