简体   繁体   中英

Efficient way to count big number on list python

What is the efficient way to count amount of the number in Array?

Here is my code:

a = 1000000000000

simpan1 = []

for i in range(a):
    if i % 75 == 0 and i >= 100:
        hasil = i
        simpan1.append(hasil)
    else:
        continue

print("The amount of the number:", len(simpan1))

it took a lot of time to count it, so I hope there's a quicker way to do it. Thanks!

You have numbers from 0 to (1000000000000 - 1) and you need to know how many numbers are bigger than or equal to 100 and when divided by 75 yields no remainder.

you can simply do this by dividing (1000000000000 - 1) which is (999999999999) over 75 this will simply calculate the amount of numbers which when divided by 75 yields no remainder, of course, you will ignore the fractional part of the answer.

Now you simply must subtract one from the final answer.

Why?

because you want the numbers which satisfy the condition and bigger than 100 or equal and you know that there is one number less than 100 and satisfies the condition which is 75 itself so you subtract it from the final answer.

Please Note:

when you divide 999999999999 by 75 it calculates the amount of numbers between 0 and 999999999999 which are divisible by 75.

This code is equivalent and much faster:

a = 1000000000000
simpan1 = list(range(150, a, 75))
print("The amount of the number:", len(simpan1))

If you don't care about the actual numbers, this is even faster:

a = 1000000000000
print("The amount of the number:", (a - 1) // 75 - 1)

Why don't you apply math algorithm on this problem? We can count by formula below:

import math
result = math.floor((1000000000000)/75.0) - 1 #except 75

I hope this could help you.

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