黎曼zeta函数的c++实现

#include
using namespace std;
template<class T>
T Zeta(T s,double prec){
	if(s<0&&(int)s==s&&(int)-s%2==0) return T(0);
	T sc=static_cast<T>(1 - static_cast<T>(s));
	T sum=0,mult=0.5,change;
	T powers[100000]={0,};//cache有多大开多大
	unsigned n=0;
	do{
		T binom=-static_cast<T>(n);
		T ns=1;
		if(n < sizeof(powers) / sizeof(powers[0])) powers[n] = pow(static_cast<T>(n + 1), -s);
		for(unsigned k = 1; k <= n; ++k)
      {
         T p;
         if(k < sizeof(powers) / sizeof(powers[0]))
         {
            p = powers[k];
         }
         else
            p = pow(static_cast<T>(k + 1), -s);
         ns += binom * p;
        binom *= (k - static_cast<T>(n)) / (k + 1);
      }
      change = mult * ns;
      sum += change;
      mult /= 2;
      ++n;
	}while(fabs(change/sum)>prec);
	return sum * 1 /-(pow(T(2),sc)-1);
}

缩短版

#include
using namespace std;template<class T>T Zeta(T s,double prec){if(s<0&&(int)s==s&&(int)-s%2==0) return T(0);T sc=static_cast<T>(1 - static_cast<T>(s));T sum=0,mult=0.5,change;T powers[100000]={0,};unsigned n=0;do{T binom=-static_cast<T>(n);T ns=1;if(n < sizeof(powers) / sizeof(powers[0])) powers[n] = pow(static_cast<T>(n + 1), -s);for(unsigned k = 1; k <= n; ++k){T p;if(k < sizeof(powers) / sizeof(powers[0])){p = powers[k];}else p = pow(static_cast<T>(k + 1), -s);ns += binom * p;binom *= (k - static_cast<T>(n)) / (k + 1);}change = mult * ns;sum += change;mult /= 2;++n;}while(fabs(change/sum)>prec);return sum * 1 /-(pow(T(2),sc)-1);}

你可能感兴趣的:(算法)