I've got it mostly working. It segfaults under a few circumstances, mostly those where the N can't be divided without remainder with P. Working on that later