A magnesium atom needs to lose two electrons, whereas the nitrogen atom needs to gain three electrons to attain the octet.The chemical formula for magnesium nitride is Mg3N2. Two magnesium atoms donate two electrons to each nitrogen atom while one magnesium atom donates one electron to each of the nitrogen atom. Hence, an ionic bond is formed. Magnesium and nitrogen, thus, attain stability by gaining the octet state.