It originated from sanpei no gi or sanpeisen no gi (both meaning the ceremony of scattering rice cakes or coins), which was a Shinto ritual held during jotoshiki (also called tatemae) and other ceremonies for praying there would be no problem with the building, and this ritual developed into - and became popular as - mochimaki.
由来は、上棟式（建前）などで災いを払うために行われた神事である散餅の儀（もしくは散餅銭の儀）が発展的に広まったものである。