problem 41 works, but when n gets bigs it gets slow (which is expected), can be sped up though at the cost of using slightly more memory