题目描述
拓拓刚学会素数,现在回到家,他妈妈想考验一下拓拓学的怎么样。于是问了他一个问题:给你一个整数,你能说出他是不是素数吗?现在拓拓算的很慢,想请你帮忙写个程序:计算一个数是不是素数,如果是,则输出"is prime";否则输出"is not prime"。
输入格式
第一行一个整数 n。 ( 0≤n≤10000,0000,0000,00000 )
输出格式
输出这个数是不是素数。
样例
输入数据 #1
1000
输出数据 #1
1000 is not prime
输入数据 #2
97
输出数据 #2
97 is prime
数据范围
- 对于 100% 的测试数据满足: 0≤n≤10000,0000,0000,00000 。
解析
这题让判断素数(也就是质数)
NOTE
0≤n≤10000,0000,0000,00000 数据有点大哦
所以第一版
cpp
//别着急copy
#include<bits/stdc++.h>
using namespace std;
int sushu(int x){
if(x<2){
return 0;
}
int i;
for(i=2;i<=sqrt(x);i++){
if(x%i==0){
return 0;
}
}
return 1;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin>>n;
if(sushu(n)){
cout<<n<<' '<<"is prime";
}
else{
cout<<n<<' '<<"is not prime";
}
}
But
这很明显会WA,因为n的范围太大了
int很明显会爆
So,第二版
cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n;
cin >> n;
if (n < 2) {
cout << n << " is not prime";
return 0;
}
if (n == 2) {
cout << n << " is prime";
return 0;
}
if (n % 2 == 0) {
cout << n << " is not prime";
return 0;
}
for (long long i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
cout << n << " is not prime";
return 0;
}
}
cout << n << " is prime";
return 0;
}
But
这种写法太啰嗦了
So
还有一种写法
cpp
#include<bits/stdc++.h>
using namespace std;
long long sushu(long long x){
if(x<2){
return 0;
}
long long i;
for(i=2;i<=sqrt(x);i++){
if(x%i==0){
return 0;
}
}
return 1;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long n;
cin>>n;
if(sushu(n)){
cout<<n<<' '<<"is prime";
}
else{
cout<<n<<' '<<"is not prime";
}
}
直接用函数就可以了
OK, 恭喜又解决了一道难题(对于我这种 蒟蒻来讲**)**