A faster, cleaner solution based on math