Mykhaylo Fomenko's men needed to win their own match but also for England to drop points against Poland at Wembley in order to finish top of the pile.
The scoring began after just 13 minutes with a penalty from Yevhen Seleznyov after Andriy Yarmolenko was sent tumbling to the ground by Alessandro Della Valle.
The home side had barely registered that goal when they conceded again, with Yarmolenko again playing a role with the pass that teed up Devic for a neat finish into the bottom left corner.
It was then 3-0 after 19 minutes thanks to Seleznyov's header, but Ukraine had to wait until six minutes into the second half to add to their tally.
That honour fell to Devic, who headed in his second of the match, and that opened the floodgates once more with Yarmolenko getting the goal his performance deserved with a drilled effort into the top right corner after 55 minutes.
The horror show continued for San Marino with the dismissal of Mirko Palazzi minutes later for an ugly challenge on Devic which also resulted in a penalty, taken successfully by the Metalist Kharkiv striker for his hat-trick.
Vitaliy Mandzyuk rounded off the scoring with another fine header in the final minute, but the result failed to secure them the top-placed finish they had desperately hoped for.