1、算數基本定理及推論:ios
算數基本定理算法
任何一個大於1的天然數N,若是N不爲質數,均可以惟一分解成有限個質數的乘積
,這裏
均爲質數,其諸指數
是正整數。ide
這樣的分解稱爲N的標準分解式。spa
推論13d
算數基本定理中N的正約數個數爲:
。code
簡單證實一下:根據算數基本定理 可知,對於其中的任意一個pi(i∈[1,n]),其指數取0~ai範圍任何值均能組成N的不一樣的約數,故pi的指數取法就有(ai+1)種,因此N的約數總個數即爲全部質因子p的指數取法之積(乘法原理)。blog
模板題連接:約數個數get
代碼以下:it
#include <iostream> #include <algorithm> #include <cstdio> #include <vector> #include <cmath> #include <map> using namespace std; const int N =100+10, mod = 1e9 + 7; int n; map<int,int> t; void divide(int x) { for(int i=2;i<=sqrt(x);i++) { if(x%i==0) { int ans=0; while(x%i==0) { ans++; x/=i; } t[i]+=ans; } } if(x>1)t[x]+=1; return; } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { int a;scanf("%d",&a); divide(a); } long long ans=1; for (map<int,int>::iterator i = t.begin(); i != t.end(); i ++ ) { ans=ans * (long long)(i->second+1) % mod; } printf("%d\n",ans); }
推論2io
算數基本定理中N的全部正約數的和爲:
也簡單證實一下:要求N的全部正約數之和,只須要組合出全部N的正約數便可,不難發現,將上式展開後的全部項便是N的全部正約數。
模板題連接:約數之和
代碼以下:
#include <iostream> #include <algorithm> #include <cstdio> #include <vector> #include <cmath> #include <map> using namespace std; const int N =100+10, mod = 1e9 + 7; int n; map<int,int> t; void divide(int x) { for(int i=2;i<=sqrt(x);i++) { if(x%i==0) { int ans=0; while(x%i==0) { ans++; x/=i; } t[i]+=ans; } } if(x>1)t[x]+=1; return; } int qin(int p,int a) { int res=1; for(int i=1;i<=a;i++) { res=((long long)res*p+1)%mod; } return res; } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { int a;scanf("%d",&a); divide(a); } long long ans=1; for (map<int,int>::iterator i = t.begin(); i != t.end(); i ++ ) { int p=i->first,a=i->second; ans=(long long)ans * qin(p,a) % mod; } printf("%d\n",ans); }
2、歐幾里得算法
對於任意的a,b∈N,b≠0,gcd(a,b) = gcd(b,a mod b),其中gcd(a,b)表示a和b的最大公約數。
下面給出證實:
證實:
要證實gcd(a,b)=gcd(b,a mod b),只要證實gcd(a,b)≤gcd(a,a mod b),且gcd(a,b)≥gcd(b,a mod b)。
下面證實gcd(a,b)≤gcd(b,a mod b):
設d是a和b的最大公約數,因此d | a且d | b,能夠推出 d | a mod b。
假設a=k*b+r(k,r均是整數,且0≤r<b),由於d | b,因此d | kb,又由於d | a,因此d | (a - kb),即d | (a mod b)。
至關於咱們有了這樣的結論:d是a和b的最大公約數,且d又是(a mod b)的約數,因此d是b和(a mod b)的公約數,因而即可推出gcd(a,b)≤gcd(b,a mod b)。
下面證實gcd(a,b)≥gcd(b,a mod b):
設d是b和(a mod b)的最大公約數,因此d | b且d | (a mod b),能夠推出 d | a。
假設a=k*b+r(k,r均是整數,且0≤r<b),由於d | b,因此d | kb,又由於d | (a - kb),因此 d | (kb + (a - kb)),即 d | a。
至關於:d是a和(a mod b)的最大公約數,且d又是a的約數,因此d是a和b的公約數,因而即可推出gcd(a,b)≥gcd(b,a mod b)。
證畢!
模板題連接:最大公約數
代碼實現:
int gcd(int a,int b) { return b ? gcd(b,a%b) : a; }