质数检验
题目18.1链接Prime Numbers
两种方法:
- 检验质数法
- 埃拉托色尼筛选法(把范围内的质数全选出来)
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAX = 10000005;
bool isPrime(int t)//检验质数法
{
if(t==2) return 1;
if(t<2 || t%2==0) return 0;
for(int i=3; i*i<=t; i+=2)
{
if(t%i==0)
return 0;
}
return 1;
}
int isprime[MAX];
void eratos(int n)//埃拉托色尼筛选法
{
memset(isprime, -1, sizeof(isprime));
isprime[0] = isprime[1] = 0;
for(int i=2; i<=n; i++)
{
if(isprime[i]==0) continue;
int j=i*i;//技巧,i*k(k<i)一定已经被标记过了
while(j<=n)
{
isprime[j] = 0;
j += i;
}
}
}
int main()
{
int n, t, ans = 0;
scanf("%d", &n);
eratos(MAX-1);
for(int i=0; i<n; i++)
{
scanf("%d", &t);
//if(isPrime(t)) ans++;
if(isprime[t]) ans++;
}
printf("%d\n", ans);
return 0;
}
最大公约数
题目18.2链接Greatest Common Divisor
欧几里得算法
#include <iostream>
#include <algorithm>
using namespace std;
int gcd(int x, int y)
{
int r;
if(x<y) swap(x, y);
while(y>0)
{
r = x%y;
x = y;
y = r;
}
return x;
}
int main()
{
int x, y;
cin >> x >> y;
int d = gcd(x, y);
cout << d << endl;
return 0;
}
幂乘
题目18.3链接Power
#include <iostream>
using namespace std;
typedef long long LL;
const int MAX = 1000000007;
LL Power(LL m, LL n)
{
LL res = 1;
while(n>0)
{
if(n&1) res = res*m%MAX;//n为奇数时将上一次计算的值乘起来
m = m*m%MAX;
n >>= 1;//n除以2
}
return res;
}
int main()
{
LL m, n;
cin >> m >> n;
LL res = Power(m, n);
cout << res << endl;
return 0;
}