Problem 39 (BruteForce & Optimized Version)