M, 19 bytes
M is just Jelly but with Sympy. Explanation to come. This program is longer than it should be because M is a very old version of Jelly. I will add the golfed Jelly version later.
Jelly, 1411 bytes
Shorter with the new Jelly features.Try it online!