线性筛法求素数:
int calc_prime(int N) {//N 为要求1-N内的素数,返回素数的个数 int i,j,len = 0; for(i=2; i< N; i++) { if(!flag[i])prime[len++]=i; for(j=0; j<len&&prime[j]*i< N; j++) { flag[prime[j]*i]=true; if(i%prime[j]==0)break; } } /*for(i = 0; i < len; i++){ cout<<prime[i]<<' '; } cout<<endl;*/ return len; }
欧拉函数:
求N的欧拉函数值:
int euler(int n){ //返回euler(n) int res=n,a=n; for(int i=2;i*i<=a;i++){ if(a%i==0){ res=res/i*(i-1);//先进行除法是为了防止中间数据的溢出 while(a%i==0) a/=i; } } if(a>1) res=res/a*(a-1); return res; }
求1-N所有数的欧拉函数值:
void Init(){ euler[1] = 1; for(int i = 2; i < N; i++) euler[i] = i; for(int i = 2; i < N;i ++) if(euler[i] == i) for(int j = i;j < N;j += i) euler[j] = euler[j] / i * (i - 1);//先进行除法是为了防止中间数据的溢出 }
利用矩阵快速幂 快速求出第n个斐波那契数:
#include <iostream> #define MAX 10000000 using namespace std; #define N 2 #define ll long long const int M = 1000000007; struct Matrix { int v[N][N]; }; Matrix A={ 1,1, 1,0 },B={ 1,0, 0,1 }; Matrix mul(Matrix m1,Matrix m2){ int i,j,k; Matrix c; for(i=0;i<N;i++)for(j=0;j<N;j++){ c.v[i][j]=0; for(k=0;k<N;k++) c.v[i][j]+=(m1.v[i][k]*m2.v[k][j]); } return c; } Matrix Mpow(Matrix A,Matrix B,int n,ll M){ Matrix x=A,c=B; while(n>=1){ if(n&1)c=mul(c,x,M); n>>=1; x=mul(x,x,M); } return c; } int main() { int i,j; x = 6; Matrix p = Mpow(A,B,x,M);//求得第x+1个斐波那契数在p.v[0][0] cout<<p.v[0][0]<< endl; return 0; }
参考文本:
http://hi.baidu.com/yxdark/item/25e436100d775d3eb8318046
http://blog.163.com/archer_nzy/blog/static/13338258220115210852869/
http://wenku.baidu.com/view/297928ea81c758f5f61f67a9.html
http://blog.csdn.net/once_hnu/article/details/6302868
http://www.cnblogs.com/DreamUp/archive/2010/07/24/1784116.html
http://blog.csdn.net/mbxc816/article/details/7214872