Practice question AMBOXES : runtime error(NZEC) even when the code runs perfectly on CodeChef IDE

For the following question,
Nested Candy Boxes
I submitted the following code as a response:

-----------------------------Start of Code-----------------------------

import java.util.Scanner;
class Main{
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int n = input.nextInt(), m = input.nextInt();

        int[] a = new int[n+1];
        int[] X = new int[m];
        for(int i=1;i<=n;i++) {
            a[i] = input.nextInt();
        }
        for(int i=0;i<m;i++) {
            X[i] = input.nextInt();
        }

        for(int i=0;i<m;i++) {
            int[] boxOpened = new int[n+1];

            boxOpened[0] = X[i];
            for(int j=1;j<=n;j++) {
                boxOpened[j] = boxOpened[j-1]%a[j]==0? boxOpened[j-1]/a[j] : boxOpened[j-1]/a[j]+1;
            }

            int sum = 0;
            for(int j=1;j<=n;j++) {
                sum += boxOpened[j];
            }
            System.out.println(sum);
        }
    }
}

------------------------------End of Code------------------------------

But I kept getting “runtime error(NZEC)”
Please provide suggestions on how to edit my code so as to prevent this error.

Each element of array X[] can be upto 10^12. But ‘int’ can store upto (2^32 -1). Use ‘long’ for X[]. Obviously, ‘sum’ and ‘boxOpened[]’ must be ‘long’ too.

Now, the RE should change to TLE…:slight_smile:

as your logic is O(2mn + m +n ) == O(mn)

#which would clearly not pass in 4 secs in java… hence you need to optimize you logic too…
Hope you’ll try logic by yourself rather then asking about it…

After you optimize the logic and still get NZEC (maybe u can try submitting same logic in c or c++ if u get NZEC even after several optimizations)

It can be because using scanner class makes your code very slow… hence another way of taking inputs fast should be used… I have already implemented that on you **


[1]** , have a look...  
#moreover , the inputs are upto 10^12 which is I guess out of bounds of int so I suggest you to use "$long$" instead of "$int$"  


  [1]: https://www.codechef.com/viewsolution/18707021

this is general soln to get rid of NZEC…
some other problems throwing NZEC are

div by 0

infinite recursion

#which are not the cause of your error…

thanks for 2 extra reputations… :slight_smile: