other's elegant algorithm, I didn't recognize this is a GCD problem, shame