Copied over Problem846 from previously solved AOAPC problem set