Counting multiples of an integer is giving very different values than expected

Asked

Viewed 444 times

0

When receiving two integer numbers, I have to show how many multiples the number n1 (typed 3) has until you reach the n2 (typed 44).

The right result should be:

The number 3 has 14 multiples smaller than 44.

The problem is that my result is giving:

The number 3 has 6 multiples smaller than 44

That is the code:

n1 = int(input())
n2 = int(input())
soma = 0
count = -1
for c in range(n1, n2, 2):
  if c % 3 == 0:
    soma += c
    count += 1
print('O numero {} tem {} multiplos menores que {}.'.format(n1, count, n2))
  • 2

    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

6 answers

4

I imagine that’s what you wish:

n1 = int(input())
n2 = int(input())
count = 0
for c in range(n1, n2):
    if c % n1 == 0:
        count += 1
print('O numero {} tem {} multiplos menores que {}.'.format(n1, count, n2))

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I don’t understand what the sum does there, I did. I do not know why you decided to jump 2 by 2. There may be some reason, it may be that the statement is incomplete or ambiguous. I understood that the first number typed would be to indicate the multiples.

I interpreted that it itself would be a valid last so I started counting with 0, but if really it should not be counted it should start with -1, I went in the most logical. it seems that not for the result that is waiting.

And the biggest error of the code is that it is using the fixed multiple 3, which seems wrong, may be until it is the right one and is not clear, being the multiple of the first number typed then it is this variable that should use as divisor.

A more idiomatic form:

n1 = int(input())
n2 = int(input())
count = 0
for c in range(n1, n2, n1):
    count += 1
print('O numero {} tem {} multiplos menores que {}.'.format(n1, count, n2))

2

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

2

An alternative solution to the problem would be to create a numerical list [n1, n2[ and filter their values by passing only the multiples of n1 and count the quantity of those approved values.

To filter a list use the builtin function filter(function, iterable) building an iterator from the elements of iterable for which function returns True.

The filter function is an anonymous function created with the keyword lambda:

#Se x for múltiplo de n1 retorna True
lambda x: x % n1 == 0

To count the elements we use the builtin function len(s) that returns the number of items in an object.

To facilitate assembly the output string was used fstring.

n1 = int(input("número a ser testado: "))
n2 = int(input("limite do teste: "))

count = len(list(filter(lambda x: x % n1 == 0, range(n1, n2))))

print(f'O numero {n1} tem {count} multiplos menores que {n2}.')

Test in Repl.it: https://repl.it/repls/LumberingEvenDisassembler

1

In Python, you can solve the proposed problem without any kind of loop, look at you:

n1 = int(input())
n2 = int(input())

count = len(range(n1, n2, n1))

print('O numero {} tem {} multiplos menores que {}.'.format(n1, count, n2))

See working on Repl.it

0

From what I understand, you intend to contar the amount of múltiplos of a certain value that lies within a range in which the menor value is n1 and the maior value is n2.

To solve this question, you can use the following algorithm...

print('=' * 55)
print(f'\033[34m{f"Contador de Múltiplos":^55}\033[m')
print('=' * 55)

while True:
    try:
        n1 = int(input('Digite o limite inferior: '))
        break
    except:
        print('\033[31mValor INVÁLIDO! Digite apens números inteiros!\033[m')

while True:
    try:
        n2 = int(input('Digite o limite superior: '))
        break
    except:
        print('\033[31mValor INVÁLIDO! Digite apens números inteiros!\033[m')

cont = 0
for c in range(n1, n2 + 1, n1):
    cont += 1
print(f'\033[32mTemos {cont} múltiplos de {n1} no intervalo fechado [{n1}, {n2}]')

See here the functioning of the algorithm.

Note that this algorithm has error handling and exception for each valor digitado.

-2

    print('-=-'*20)
    print('Multiplos de 3.')
    print('-=-'*20)

    n1 = int(input())
    n2 = int(input())
    cont = 0
    for c in range(n1,n2):
        if c % n1 ==0:
            cont = + 1

   print(f'O numero {n1} tem {count} multiplos menores que {n2}')

See yes so you managed to solve your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.