user3333899
user3333899

Reputation: 1

How many integers between 1 and 1000 inclusive that are not divisible by 3, 5 or 7?

I am using Python and can someone please tell me what is wrong with my code here?

def notdivisible():

    count =0
    for i in range(1,1001):

        while i%3 !=0 or i%5 !=0 or i%7 !=0:
            count+=1
            i+=1

    print (count)


notdivisible()

Upvotes: 0

Views: 3035

Answers (4)

dugres
dugres

Reputation: 13103

sum(1 for i in range(1, 1001) if i%3 and i%5 and i%7)  

EDIT:
I'm not sure what the question actually is ; you could use "or" or "and" as needed ...

Upvotes: 1

wim
wim

Reputation: 363133

Just a different idea ...

>>> x = range(1001)
>>> len(set(x) - set(x[::3]) - set(x[::5]) - set(x[::7]))
457

p.s. the problem with your code was that line with the while: the while should have been an if, with each or changed to and.

Upvotes: 1

MxLDevs
MxLDevs

Reputation: 19546

In your while loop you have a i+=1, which is the variable that you're using in the for loop. This is causing you to skip numbers and probably why your code is not returning the expected value.

The loop variable is automatically incremented with each iteration. You don't have to update it yourself (unless that's what you actually want to do).

Upvotes: 0

Hugh Bothwell
Hugh Bothwell

Reputation: 56674

count = 0
for i in range(1,1001):
    if i%3 and i%5 and i%7:
        count += 1
print(count)

You don't need a while loop, the for takes care of incrementing i.

Upvotes: 6

Related Questions