Other respondents have already mentioned several optimizations that will help. However, in the long run, you will not be able to map C performance in Python. Python is a great tool, but since it is interpreted, it is not suitable for heavy crunches or other applications where performance is key.
Also, even in your version of C, your inner loop might use some help. Updated Version:
for(i = 1; i < maxNumber; i++){ for(g = 1; g < maxNumber; g++){ if(i == g) continue; max=i; min=g; if (max<min) { // xor swap - could use swap(p_max,p_min) instead. max=max^min; min=max^min; max=max^min; } p_max=P(max); p_min=P(min); p_i=P(i); p_g=P(g); if(p_max - p_min < diff && fullCheck(p_max-p_min) && fullCheck(p_i + p_g)){ diff = p_max - p_min; printf("We have a couple %llu %llu with diff %llu\n", p_i, p_g, diff); } } } /////////////////////////// float fullCheck(int number){ float den=sqrt(1+24*number)/6.0; float check = 1/6.0 - den; float check2 = 1/6.0 + den; if(check == (int)check) return check; if(check2 == (int)check2) return check2; return 0.0; }
Department, function calls, etc. are expensive. Also, calculating them once and storing them in vars, as I did, can make things more readable.
You might consider declaring P () as inline, or rewrite it as a preprocessor macro. Depending on how good your optimizer is, you can do some arithmetic yourself and simplify its implementation.
Your implementation of fullCheck () will return what seems unacceptable, since 1/6 == 0, where 1 / 6.0 will return 0.166 ... as you would expect.
This is a very brief question about what you can do for your C code to improve performance. This will no doubt widen the gap between C and Python performance.
source share