completed algorithm, but results are not correct when comparing to wolfram