Birthday Example[Back] The Birthday attack equation determines the probability of two people having the same birthday given n people. It uses a general form of: Sample codeIn this case we can use now use Big Integers to determine the values, as we are using mathematical functions which will overflow normal data types: public string birth2(double val1, double val2) { Microsoft.SolverFoundation.Common.BigInteger v1,v2,res; v1=(Microsoft.SolverFoundation.Common.BigInteger)val1; v2=(Microsoft.SolverFoundation.Common.BigInteger)val2; Microsoft.SolverFoundation.Common.BigInteger num = Microsoft.SolverFoundation.Common.BigInteger.Factorial(v1); Microsoft.SolverFoundation.Common.BigInteger den1 = Microsoft.SolverFoundation.Common.BigInteger.Power(v1, v2); Microsoft.SolverFoundation.Common.BigInteger den2 = Microsoft.SolverFoundation.Common.BigInteger.Factorial(v1 - v2); // Multiple by 10000 as we want three decimal places res = (Microsoft.SolverFoundation.Common.BigInteger)(100000*num) / ((Microsoft.SolverFoundation.Common.BigInteger)den1 * (Microsoft.SolverFoundation.Common.BigInteger)den2); double res_result = (double)res; return (String.Format("{0:0.000}%", 100-res_result/1000)); } The code uses a reference of Microsoft.Solver.Foundation.dll which is typically stored in the C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0 directory. Try an example
The equivalent code using standard data types is: public string birth(double val1, double val2) { double counter = val1; double res = 1; for (int i = 0; i < ((int)val1 - (int)(val1 - val2)); i++) { res = res * counter; counter = counter - 1; } res = 1 - (res / (double)Math.Pow((double)val1, (double)val2)); return (String.Format("{0:0.00}%", 100 * res)); } |