素数:
#include <iostream>
using namespace std;
bool isPrime(int n){
if(n<2)return false;
for(int i=2;i*i<=n;i++){
if(n%i==0)return false;
}
return true;
}
int main(){
int n;
cin>>n;
cout<<isPrime(n);
return 0;
}
因数分解:
#include <bits/stdc++.h>
using namespace std;
int main(){
long long n;
cin>>n;
long long i=2;
bool f=true;// 标记是不是第1个质因数
while(i*i<=n){
if(n%i!=0){ // 不是质因数直接跳过
i++;
continue;
}
int c=0; // 统计相同i的个数
while(n%i==0){
// cout<<i<<" ";
c++;
n/=i;
}
if(f)f=false;
else cout<<" * ";
cout<<i; //输出质因数i
// 如果c>1,按照指数形式输出质因数i
if(c>1)cout<<"^"<<c;
i++;
}
// 如果存在超过平方根的质因数
if(n>1){
f?cout<<n:cout<<" * "<<n;
}
return 0;
}
小杨的幸运数:
#include <iostream>
using namespace std;
int cal(int n){
int i=2;
int s=0;
while(i*i<=n){
if(n%i!=0){
i++;
continue;
}
while(n%i==0){
n/=i;
}
s++;
i++;
}
// 如果存在超过平方根的质因数
if(n>1)s++;
return s;
}
int main(){
int t;
cin>>t;
while(t--){
int x;
cin>>x;
if(cal(x)==2)cout<<1<<endl;
else cout<<0<<endl;
}
return 0;
}
小杨的幸运数(set)
#include <iostream>
#include <set>
using namespace std;
int cal(int n) {
set<int> prime_factors; // 用set来存储质因子
int i = 2;
while (i * i <= n) {
if (n % i != 0) {
i++;
continue;
}
while (n % i == 0) {
prime_factors.insert(i); // 将质因子插入set
n /= i;
}
i++;
}
// 如果剩余的n大于1,说明n本身是一个质因子
if (n > 1) {
prime_factors.insert(n);
}
return prime_factors.size(); // 返回不同质因子的数量
}
int main() {
int t;
cin >> t;
while (t--) {
int x;
cin >> x;
if (cal(x) == 2) {
cout << 1 << endl;
} else {
cout << 0 << endl;
}
}
return 0;
}
B-smooth数:
#include <iostream>
using namespace std;
// 计算最大质因数
int cal(int n){
int i=2;
int mx=1;
while(i*i<=n){
if(n%i!=0){
i++;
continue;
}
while(n%i==0){
n/=i;
}
mx=max(mx,i);
i++;
}
if(n>1)mx=n;
return mx;
}
int main(){
int n,b;
cin>>n>>b;
int cnt=0;
for(int i=1;i<=n;i++){
if(cal(i)<=b)cnt++;
}
cout<<cnt;
return 0;
}