It's a bug in MC15 (I'm using M030, so it's not specific to M040). The program that calculates Ap is run for each value of the range variable J. Each of these runs should be independent of any previous run, but in MC15 they are not. Specifically, A is not reinitialized. For J=1 that doesn't matter because there are more rows than there were for J=0. But J=2 and J=3 have fewer rows than J=1, and the extra rows in A are left tacked onto the end. It can be fixed by explicitly initializing A to 0 before the for loop:

Note that I also got rid of the first for loop. I'm not sure what that was supposed to do, but if it was supposed to initialize i to some value it's a terrible way to do it. It would only do that if it is assumed that the loop will run even though there is nothing in the loop that assigns any value to any variable. That's a bad assumption, because any half way decent optimization will recognize that, and remove the loop. I'm a little surprised it even initialized i to 0. If i does need to be initialized to a value other than 0 then it needs to be done in a reliable way.
Edit: The bug also exists in MC13. I don't have MC12 installed, but I assume it was introduced when Mathsoft rewrote the compute engine for MC12. Or maybe it was a new "feature". Plenty of "features" that many users considered to be bugs were introduced in MC12! As to why it works in Prime, who knows. Was it deliberately fixed, but left unfixed in MC15, or was it accidentally fixed?