count to a billion in python

To count to a billion in Python, we can use a for loop and the built-in range() function. However, a loop with a range of one billion would take a long time to complete. So, we can break it down into smaller chunks using the math.ceil() function to round up the number of iterations needed for each chunk.

main.py
import math

# set the total number to count to
total_count = 1000000000

# set the chunk size to 10 million
chunk_size = 10000000

# calculate the number of chunks needed
num_chunks = math.ceil(total_count / chunk_size)

# loop through each chunk
for i in range(num_chunks):
    # calculate the range for this chunk
    start = i * chunk_size
    end = min(start + chunk_size, total_count)
    
    # loop through the numbers in this chunk
    for j in range(start, end):
        print(j)
490 chars
21 lines

This code will count from 0 to 999999999, printing each number along the way. The chunk_size variable can be adjusted to balance performance with memory usage.

gistlibby LogSnag