#2012
题目直达:http://acm.hdu.edu.cn/showproblem.php?pid=2012
其实就是一个简单的素数判断的算法
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
int main() {
int x,y;
while(cin>>x>>y) {
if(x==0 && y==0) {
return 0;
}
int flag=0;
for(int i=x; i<=y; i++) {
int res=i*i+i+41;
for(int j=2; j<=sqrt(res); j++) {
if(res%j==0) {
flag++;
}
}
}
if(flag==0) {
cout<<"OK"<<endl;
} else if(flag!=0) {
cout<<"Sorry"<<endl;
}
}
return 0;
}
这里记录一下素数判定的一些方法
首先需要对素数的定义有一定的了解
1不是素数,素数是指一个大于1的自然数,除了1和它本身外,不能被其他自然数(质数)整除。
定义法
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
int main() {
int n;
while(cin>>n) {
int flag=0;
for(int i=2;i<n;i++){
if(n%i==0){
flag++;
}
}
if(flag==0){
cout<<n<<" is a prime."<<endl;
}
else cout<<n<<" is not a prime."<<endl;
}
return 0;
}
加速法:将判定范围缩减,计算到平方根即可,如果有因子,则因子也一定出现在其平方根内
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
int main() {
int n;
while(cin>>n) {
int flag=0;
for(int i=2;i<=sqrt(n);i++){
if(n%i==0){
flag++;
}
}
if(flag==0){
cout<<n<<" is a prime."<<endl;
}
else cout<<n<<" is not a prime."<<endl;
}
return 0;
}
素数筛选法:以找到的素数为筛选标准,去掉其倍数,得到的就是素数。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
int main() {
int n;
while(cin>>n) {
int flag=0;
if(n%2==0) {
flag++;
}
for(int i=3; i<=sqrt(n); i++) {
if(i%2!=0) {
for(int j=2*i; j<=n; j+=i) {
if(n==j) {
flag++;
}
}
}
}
if(flag==0) {
cout<<n<<" is a prime."<<endl;
} else {
cout<<n<<" is not a prime."<<endl;
}
}
return 0;
}