简体   繁体   中英

How can I count numbers in the given range?

So I wrote a code which lists all the numbers that are not divisible by 2 and 3. Now I would like to know how many of those numbers are in rage 1000. After googling a bit I haven't found anything that can help me with my case.

Could you guys give me some tips? Would appreciate it!

for i in range(1, 1000):

    if i%2 != 0 and i%3 != 0:

        print(i)

The range is already defined, put a count

count = 0
for i in range(1, 1000):
    if i%2 != 0 and i%3 != 0:
        count += 1
        print("The number is {}".format(i))   
print("Count: {}".format(count))

OUTPUT :

The number is 1
The number is 5
The number is 7
The number is 11
The number is 13
.
.
.
The number is 991
The number is 995
The number is 997
Count: 333

EDIT :

one-liner

print("Count: {}".format(sum(1 for i in range(1000) if i%2 != 0 and i%3 != 0)))
count=0

for i in range(1, 1000):

if i%2 != 0 and i%3 != 0:
    count=count+1
    print(i)

just make a count inside a IF block

There are 1000/2 = 500 numbers divisible by 2 and 1000/3 = 333 divisible by 3. Among these, the multiples of 6 appear twice and there are 1000/6 = 165 of them.

Hence 1000 - (500 + 333 - 166) = 333.

Up to a billion billion, you would have 1,000,000,000,000,000,000 - (500,000,000,000,000,000 - 333,333,333,333,333,333 - 166,666,666,666,666,666) = 333,333,333,333,333,333 of them, which is just a third.

The simplest solution is to put a count variable in your loop and increment it.

count = 0
for i in range(1, 1000):
if i%2 != 0 and i%3 != 0:
    count+=1
    print(i)
print(count)

Another solution might be:

count = len([x for x in range(1,1000) if x%2!=0 and x%3!=0])
def number_of_not_divisible(a, b, myrange):
result = 0
least_common_multiple = a * b
while myrange % least_common_multiple != 0:
    if myrange % a != 0 and myrange % b != 0:
        result += 1
    myrange -= 1
partial_result_inside_one_range = 0
for i in range(least_common_multiple):
    if i % a != 0 and i % b != 0:
        partial_result_inside_one_range += 1

result += partial_result_inside_one_range * (myrange / least_common_multiple)
print(result)

number_of_not_divisible(2, 3, 1000)

You can make it easier and general. You can see that in every interval with size of least common multiple of the two numbers, the number of searched elements are the same. So you just have to count in the first interval, and have to multiple it, and after just count, the numbers in the range%least common multiple. I think it have to work general, but tell me if you get a mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM