|
发表于 2024-1-15 15:16:13
|
显示全部楼层
对比python+gmp 和C+gmp 代码的效率,结论是:同样的算法,C的执行效率是python的三倍,- 9 0.011497s, 0.01612 315306518862563689 10 0.034581s, 0.052466 31530956879912196121 11 0.095133s, 0.164893 3153105325203283282791 12 0.234725s, 0.49664 315310838250195945316697 13 0.599286s, 1.577465 31531093463422331742627898 14 1.796593s, 4.937906 3153109651585438043478518292 15 5.764869s, 15.912529 315310974814380507221575440565 16 17.976543s, 50.962873 31531097786817229071240053411627 17 57.295435s, 159.026102 3153109788339240470789175907861511 18 182.901621s, ***** 315310979139296541791878037384668861 19 571.448696s, *** 31531097923586107532823734833133478270 20 1829.964781s, **** 3153109792663973490168308890337939863948 21 5759.034041s, ***** 315310979276053840222630577715772302609714 22 31531097927910748493556944524769918311060947 23 3153109792800731344476163185764035193616778666
复制代码
附带任意精度的版本:
- #include<gmp.h> #include<stdio.h> #include<stdlib.h> #include<stdint.h> #include<math.h> #include<sys/time.h> #include<unistd.h> int main(int cnt, char** v) { if (cnt > 1) { struct timeval start, end; gettimeofday(&start, NULL); mpz_t max, pmax, qmax, p, q, max_tmp, ans, gcd, tmp, a, b, c, k; mpz_inits(max, pmax, qmax, '\0'); mpz_inits(p, q, max_tmp, '\0'); mpz_inits(ans, gcd, tmp, '\0'); mpz_inits(a, b, c, k, '\0'); mpz_set_str(max, v[1], 10); //int64_t max = mpz_get_ui(max_tmp); mpz_root(qmax, max, 4); //int64_t qmax = mpz_get_ui(maxT); mpz_fdiv_q_ui(max_tmp, max, 4); mpz_root(pmax, max_tmp, 4); //int64_t pmax = mpz_get_ui(maxT); mpz_set_str(p, "1", 10); while (mpz_cmp(p, pmax) <= 0) { mpz_set(q, p); while (mpz_cmp(q, qmax) <= 0) { mpz_gcd(gcd, p, q); if (mpz_cmp_ui(gcd, 1) == 0) { // int g = mpz_get_ui(gcd); // if(g==1){ // uint64_t k=max/q/q/(p+q)/(p+q); // uint64_t a=p*p*(p+q)*(p+q); // uint64_t b=q*q*(p+q)*(p+q); // uint64_t c=p*p*q*q; mpz_set_str(tmp, "0", 10); mpz_set_str(max_tmp, "0", 10); //mpz_set_str(k,"1",10); mpz_set_str(a, "1", 10); mpz_set_str(b, "1", 10); mpz_set_str(c, "1", 10); mpz_add(max_tmp, p, q); mpz_fdiv_q(k, max, q); mpz_fdiv_q(k, k, q); mpz_fdiv_q(k, k, max_tmp); mpz_fdiv_q(k, k, max_tmp); mpz_mul(a, p, p); mpz_mul(a, a, max_tmp); mpz_mul(a, a, max_tmp); mpz_mul(b, q, q); mpz_mul(b, b, max_tmp); mpz_mul(b, b, max_tmp); mpz_mul(c, p, p); mpz_mul(c, c, q); mpz_mul(c, c, q); mpz_add(tmp, tmp, a); mpz_add(tmp, tmp, b); mpz_add(tmp, tmp, c); mpz_mul(tmp, tmp, k); mpz_add_ui(k, k, 1); mpz_mul(tmp, tmp, k); mpz_fdiv_q_ui(tmp, tmp, 2); mpz_add(ans, ans, tmp); // } } mpz_add_ui(q, q, 1); } mpz_add_ui(p, p, 1); } gettimeofday(&end, NULL); double diff = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000000.; gmp_printf("time:%fs, %Zd\n", diff, ans); mpz_clears(max, pmax, qmax, p, q, max_tmp, ans, gcd, tmp, a, b, c, k, '\0'); } }
复制代码 |
|