Let indicate with $v_a$ the speed of the army, by $v_h$ the speed of the horseman, then for the travel in front we have
* the position of the general is: $x_g=40+v_at$
* the position of the horseman is: $x_h=v_ht$
and
$$x_g=x_h\implies t_1=\frac{40}{v_h-v_a}$$
For the travel to return we have
* the position of the rear: $x_r=40-v_at$
* the position of the horseman is: $x_h=v_ht$
and
$$x_r=x_h\implies t_2=\frac{40}{v_h+v_a}$$
From the given condition we know that
$$(t_1+t_2)v_a=40$$
that is
$$40\frac{v_a}{v_h-v_a}+40\frac{v_a}{v_h+v_a}=40$$
$$\frac{2v_av_h}{v_h^2-v_a^2}=1 \implies v_h^2-2v_av_h-v_a^2=0 \implies v_h=(1+\sqrt2)v_a$$
and the distance traveled is therefore $40(1+\sqrt2)$ km.