implementing pham function to find best K