Optimal control theory is applied to the simulation of heating, ventilating, and air-conditioning systems in buildings. The problem is as follows: given a system of ordinary differential equations that describes the thermal behaviour of a commercial building, and its air conditioning system, try to find the optimal air conditioning policy leading to a minimum of the total energy cost.Air conditioning is obtained by pulsing air at a constant temperature. The airflow rate is chosen as the control variable. This airflow rate must, of course, satisfy some comfort constraints:It should be larger than a lower bound corresponding to the amount of air coming from the outside for evident hygienic reasonsIt should be able to maintain the temperature in the occupied zone of the building as close as possible to a target temperatureThe minimizing algorithm uses the conjugate gradient method. Integration of the ordinary differential equations is performed by a fifth order explicit Runge-Kutta-Fehlberg method, with variable step size.An original method was developed to compute the gradient without computing an adjoint differential system.Some computational results are given, and, finally the capabilities of such an algorithm and the different ways to improve the method in order to apply it to more complex systems are pointed out.