质数
试除法
记得i*i不可靠,会爆
用i<=n/i
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1E5 + 7;
#define ULL unsigned long long
#define INF ~0ULL
#define pii pair<int, int>
ll t, n, m;
ll now;
bool isprime(ll now)
{
if (now == 1)
return false;
if (now == 2)
return true;
for (int i = 2; i <= now/i; i++)
if (now % i == 0)
return false;
return true;
}
int main()
{
cin >> t;
while (t--)
{
cin >> now;
if (isprime(now))
cout << "Yes" << endl;
else
cout << "No" << endl;
}
system("pause");
}
分解质因数
n里面最多有一个因子比根号n大
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1E5 + 7;
#define ULL unsigned long long
#define INF ~0ULL
#define pii pair<int, int>
int t, n, m;
void solve(int now)
{
for (int i = 2; i <= now / i; i++)
{
if (now % i == 0)
{
int res=0;
while(now%i==0){
res++;
now/=i;
}
cout<<i<<" "<<res<<endl;
}
}
if(now>1)
cout<<now<<" "<<1<<endl;
cout<<endl;
}
int main()
{
cin >> t;
while (t--)
{
cin >> n;
solve(n);
}
system("pause");
}
筛质数
核心
const int N = 1E5 + 7;
int n, p[N], cnt;
bool vis[N];
inline void get_prime()
{
for (register int i = 2; i <= n; i++)
{
if (!vis[i]) //遇到漏网之鱼就是素数
p[++cnt] = i;
for(register int j=1;j<=cnt&&i*p[j]<=n,++j)//素数判定+越界
{
vis[i * p[j]] = 1;
if(i%p[j]==0)//i已经删过了,就不用j了
break;
}
}
}
试除法求约数
注意中间值
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1E5 + 7;
#define ULL unsigned long long
#define INF ~0ULL
#define pii pair<int, int>
int t, n, m;
int ans[N];
void solve(int n)
{
int cnt = 0;
for (int i = 1; i <= n / i; i++)
{
if (n % i == 0)
{
cout << i << " ";
ans[++cnt] = i;
}
}
if (n/ans[cnt]!=ans[cnt])
{
cout<<n/ans[cnt]<<" ";
}
for (int i = cnt - 1; i >0; i--)
{
cout<<n/ans[i]<<" ";
}
cout<<endl;
}
int main()
{
cin >> t;
while (t--)
{
cin >> n;
solve(n);
}
system("pause");
}
约数个数
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int mod = 1e9 + 7;
int main(){
int n,x;
LL ans = 1;
unordered_map<int,int> hash;
cin >> n;
while(n--){
cin >> x;
for(int i = 2;i <= x/i; ++i){
while(x % i == 0){
x /= i;
hash[i] ++;
}
}
if(x > 1) hash[x] ++;
}
for(auto i : hash) ans = ans*(i.second + 1) % mod;
cout << ans;
return 0;
}