1

I'm trying to make an algorithm, which counts how many numbers are divided without a remainder.

d=[]
for i in range (0, 10001):
    for c in range (1, 16):
        if i % c == 0: d[c] += 1

I expect to have something like this

/1:  10000
/2:  5000
/3:  3334
/4:  2500
/5:  2000
/6:  1667
/7:  1429
/8:  1250
/9:  1112
/10:  1000
/11:  910
/12:  834
/13:  770
/14:  715
/15:  667

, but i get IndexError: list index out of range

2 Answers 2

2

Just fill the list with zeros:

d = [0] * 17  # <== THIS
for i in range (0, 10001):
    for c in range (1, 16):
        if i % c == 0: d[c] += 1

Note that this has an extraneous zero at the start (i.e. d[0]). Very easy to ignore.

Also, your counts are off by one compared to what your code actually does (for example, there are 10001 even numbers in your range and not 10000).

Sign up to request clarification or add additional context in comments.

Comments

2

You can't add to an element of a list that has never been created.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.