Solved this but probably cheated as I used the prime library. Will try and make it less succint as to understand the logic