If the sequence starts with a number n1
and it should have only the multiples of that number, just iterate from n1
in n1
:
count = 0
for _ in range(n1, n2, n1):
count += 1
The third parameter of a range
is the step. If he is not informed, the value default is 1 (that is, the sequence numbers advance by 1 in 1). But I can use any other number. For example, if n1
is equal to 3, the sequence starts at 3 and jumps from 3 to 3 (i.e., it will be 3, 6, 9, etc...).
By the way, that’s why your code didn’t work, because you used step 2, so you were generating sequence 3, 5, 7, 9, etc (leaving out multiple multiples of 3, like 6, 12, 18, etc).
And how the sequence begins in n1
and the step is also n1
, then for sure all the numbers on range
will be multiples of n1
. So I don’t even need to check the rest of the split (and note that in the loop the variable is _
, which is a Python convention to indicate that I will not use the variable value, since all that matters is just counting the number of elements).
But as now we just need to know the amount of numbers range
, nor need loop, you can get it directly with len
:
count = len(range(n1, n2, n1))
I understand that being an exercise, probably "want" you to be 1 in 1 and use the operator %
. But to iterate through the multiples of a number, there’s no point in doing that, since you can generate a sequence that only has the numbers you need.
Just remembering that if n2
is multiple of n1
, it is not included in the count. For example, if n1
for 3 and n2
for 9, the result will be 2, because only 3 and 6 are considered. But if you want to consider also 9, just change to range(n1, n2 + 1, n1)
.
Although you can also solve it with good old math. Just divide n2
for n1
, and depending on the case, make appropriate adjustments.
If the idea is nay count n2
, even if it is multiple of n1
(or equivalent to range(n1, n2, n1)
), just round up the division result and subtract 1:
from math import ceil
count = ceil(n2 / n1) - 1
But if the idea is to tell n2
if it is multiple of n1
(or equivalent to range(n1, n2 + 1, n1)
), just make the entire division, using the operator //
:
count = n2 // n1
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site
– Maniero