pretty simple version, not sure it's the most efficient...
fixed it to handle even numbers better, optimized a few other things
simplified it a lot, it may be slightly less efficient, but it makes way more sense logically