 # Why is this code giving Runtime Error? - Problem Chef and Bulb Invention

Hello, I can’t seem to understand why this code is giving Runtime Error:
The problem is CHFINVNT Problem | CodeChef.
This code runs the testcases just fine.

``````import math
t = int(input())

for _ in range(t):

n,p,k = map(int,input().split(' '))

freq_leftovers = [0 for i in range(0, k)]

for j in range(0,n):
freq_leftovers[j%k]+=1

ans=0

if p%k != 0:
for l in range(0, p%k):
ans+=freq_leftovers[l]
print(ans+math.floor(p/k)+1)

else:
print(ans+math.floor(p/k)+1)
``````

Looking at the data range, you are trying to create a list of size 1e9, which gives the RTE.

1 Like

Wow that’s true, I did not think of that! Thank you!

The code you’ve provided is for a problem called “Chef and Bulb Invention” and is trying to determine the number of bulbs that can be made from a given number of leftovers.

The code seems to be mostly correct, but there is an error which is causing it to give a runtime error.

The error is in the first for loop where it is iterating from 0 to n, but it should be iterating from 0 to n-1. The reason is that the index of the list starts from 0 and the last index will be n-1.

You should change the line `for j in range(0,n):` to `for j in range(0,n-1):` this will fix the issue and the code should work as expected.

Also, there is another issue in the code, the variable `freq_leftovers` is defined with `[0 for i in range(0, k)]` which is causing it to have k element but the needed length is k-1. The reason is that the element with the index k-1 is missing.

You should change the line `freq_leftovers = [0 for i in range(0, k)]` to `freq_leftovers = [0 for i in range(0, k-1)]`.