Changed the algorithm and made more simpler