This is a typical task in general chemistry textbooks. Each such task begins with writing balanced reaction equations for each component separately, and on the basis of the stoichiometry of the equations, algebraic equations are prepared. At the level of general chemistry, the task is solved even without a calculator.
But at the level of normal chemistry, the task is unrealistic for a number of reasons: Mg reacts with HNO3 differently than, for example, Cu; the task does not take into account the NO2 ::equil::N2O4 balance (this is only a simplification that does not take into account the reduction of nitrogen oxides); under STP conditions, N2O4 is a volatile liquid. Fortunately, the problem can be solved assuming that only NO2 or only N2O4 is formed.