And what actually happened? Your title says stack overflow, but your actual question mentions an endless loop (presumably a non-responses program). These are different things and have different causes.
Stack overflows in Haskell are not caused by recursion itself, as they are in imperative languages. Haskell stack overflows are due to too much laziness.
This is a precedence issue. (f2 n d-1) is parsed as (f2 n d) - 1, which leads to infinite recursion because f2 is calling itself with the same arguments. You want f2 n (d - 1) instead.
n `mod` d == 0check. If something's divisible byd^3then it's automatically divisible byd