I am using the Kolmogorov-Smirnov test to determine if two samples of data derive from the same distribution or not. I understand how the KS statistic is calculated: Basicly it's the maximum difference between the empirical CDF of the two samples. The null hypothesis is that the samples are from the same distribution, so if the p-value is lower than alpha (say, alpha=0.05), we reject the null hypothesis and state that the two samples are from different distributions. What i don't understand is how the p-value is calculated. I am using the MATLAB KSTEST2 function. the p-value calculations is (relavnt parts):
lambda = max((sqrt(n) + 0.12 + 0.11/sqrt(n)) * KSstatistic , 0);
pValue = 2 * sum((-1).^(j-1).*exp(-2*lambda*lambda*j.^2));
pValue = min(max(pValue, 0), 1);
Setting aside the max and min that are probably just making sure lambda isn't negative and p-valus isn't above 1 or under 0, I don't understand how and why the p-value is calculated this way. Can anyone explain?