# Counting number of apples in an apple tree with given number of layers

This problem comes from a competitive programming question, and it seems to require dynamic programming.

There are several layers of apples arranged in a formation with each apple having a value associated with it. First layer contains a single apple with value equal to 2. Each apple is followed by $$(v^2+1)\mod M$$ distinct apples in the next layer having values from 0 to $$(v^2 +1)\mod M-1$$, where $$v$$ is the value of the apple. Given the total number of layers find the total number of apples modulo $$M$$.

P.S: No constraints are given for total number of layers and $$M$$.