Let's start with some ASCII art as a reference:
+-----+ +-----+
| 4 | | 5 |
| mul | | add |
--+-----+-- --+-----+--
| ° ° | | ° ° |
| A | | B |
\___/ \___/
First question to B
$B$ sees a $4$ on $A$'s hat which is the product of 2 positive integers. There are 2 possibilities:
- $1*4$ which means the sum on $B$'s hat would be $1+4=5$
- $2*2$ which means the sum on $B$'s hat would be $2+2=4$
There is no unique solution therefore $B$ must answer "No".
First question to A
$A$ sees a $5$ on $B$'s hat which is the sum of 2 positive integers. There are 2 possibilities:
- $1+4$ which means the product on $A$'s hat would be $1*4=4$
- $2+3$ which means the product on $A$'s hat would be $2*3=6$
Again no unique solution, but $A$ is not done yet. He has to check the thoughts of $B$ during his first question for each of the possibilities.
First question to A - Assuming A's number is a 4, what were B's thoughts?
We saw the possibilities for that already, and know there was no unique solution. Therefore $A$ knows that $B$ would answer "No" and must assume that a $4$ on his hat is possible.
First question to A - Assuming A's number is a 6, what were B's thoughts?
Assuming $B$ sees a $6$ on $A$'s hat which is the product of 2 positive integers, there are 2 possibilities again:
- $1*6$ which means the sum on $B$'s hat would be $1+6=7$
- $2*3$ which means the sum on $B$'s hat would be $2+3=5$
Again no unique solution, so $B$ would have to answer "No" and $A$ must assume that a $6$ on his hat is possible as well.
This means that from $A$'s point of view his hat can be either $4$ or $6$. No unique solution, so he must answer "No".
Second question to B
The possibilities for the number on $B$'s hat from $B$'s point of view are still the same: $5$ or $4$. But now he also knows $A$'s answer for his first question, so he has to analyze his thoughts as well.
Second question to B - Assuming B's number is 5, what were A's thoughts?
Again we know that already, and $B$ will come to the same conclusion. That a $5$ on his hat is possible.
Second question to B - Assuming B's number is 4, what were A's thoughts?
Assuming $A$ sees a $4$ on $B$'s hat which is the sum of 2 positive integers, there are 2 possibilities again:
- $1+3$ which means the product on $A$'s hat would be $1*3=3$
- $2+2$ which means the product on $A$'s hat would be $2*2=4$
2 possibilities, but $B$ must also analyze $A$'s thoughts based on $B$'s first answer. If $A$ would assume a $3$ on his hat, there would be only one possibility for a product ($1*3$). Therefore $A$ would know that $B$'s answer would be "Yes" during the first question. As this was not the case $A$ knows there can be no $3$ on his hat. Therefore $A$ would know there is a $4$ on his hat, which is a contradiction, because $A$ answered "No".
Now $B$ knows that there is no $4$ on his hat. There is only one possibility left ($5$) and he can answer "Yes".