Very slow solution for 311 - runs in 4h30 - sieving would probably be more efficient.