Counting periodic trajectories via topological classical mechanics