Pergunta

What I need is to show how many integers that are less than N that are not dividable by 2,3 or 5. I have managed to get the list of numbers that are less than N and are not divisible by 2,3 or 5 but I cannot for the life of me get Python to actually count how many integers there are. What I have so far is

N = int(input("\nPlease input a Number "))
if N < 0:
    print("\nThere are no answers")
else:
    for a in range(1,N+1,2):
        if a%3 !=0:
            if a%5 !=0:
Foi útil?

Solução

Try this:

N = 20

counter = 0
for a in range(1, N):
    if a%2 and a%3 and a%5:
        counter += 1

The result will be in counter at the end of the loop. Or for a fancier version, adapted from @iCodez's answer:

sum(1 for x in range(1, N) if all((x%2, x%3, x%5)))
=> 6

Outras dicas

Have you tried declaring a global variable and incrementing it?

i = 0

... if a % 5 != 0:
        i += 1

print i

This can be done quite easily using a list comprehension, all, and len:

>>> num = int(input(':'))
:20
>>> [x for x in range(num) if all((x%2, x%3, x%5))]
[1, 7, 11, 13, 17, 19]
>>> len([x for x in range(num) if all((x%2, x%3, x%5))])
6
>>>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top