In mathematics, a prime number (prime number) is a number that is only divisible by 1 or itself. Therefore, students often use the following ideas when writing code, for example, how to determine that 43 is a prime number? Then divide 43 by 2, 3, 4, 5...42, and see if there is a number that can divide 43 from 2-42. If there is, 43 is not a prime number, otherwise, 43 is a prime number. Therefore, the following code can be written:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
for(int i=2;i<n;i++){
if(n%i==0){
cout<<"合数";
return 0;//是合数直接结束
}
}
cout<<"质数";
return 0;
}
Think about it, we need violence 2 to n-1, it is too slow, how to optimize it?
Calculate by hand and
think, how much can be divided?
a/b=c...k, if a is not divisible by b, then a is not divisible by c.
We found that it is enough to divide the arithmetic square root of n, that is, sqrt(n), so optimize the sentence
for(int i=2;i<n;i++) for(int i=2;i<sqrt(n) ;i++) So, with:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
for(int i=2;i<sqrt(n);i++){
if(n%i==0){
cout<<"合数";
return 0;
}
}
cout<<"质数";
return 0;
}
However, in the for, the square root operation is performed for each cycle, which is obviously cumbersome, so the sqrt(n) is proposed, and the k=sqrt(n) operation is completed on the for.
So, with:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int k=sqrt(n);
for(int i=2;i<k;i++){
if(n%i==0){
cout<<"合数";
return 0;
}
}
cout<<"质数";
return 0;
}
The above writing method is mostly used in Xingxinaozhong.
There is another way of writing, often in ACM:
for(int i=2;i<=n/i;i++)
case1: Find all prime numbers within 100
#include<bits/stdc++.h>
using namespace std;
int main()
{
for(int i=2;i<=100;i++){
int k=sqrt(i);
int flag=0;
for(int j=2;j<=k;j++){
if(i%j==0){
flag=1;
break;
}
}
if(flag==0){
cout<<i<<" ";
}
else flag=0;
}
return 0;
}
case2: Find all prime numbers between n~m
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
if(n<2) n=2;
for(int i=n;i<=m;i++){
int k=sqrt(i);
int flag=0;
for(int j=2;j<=k;j++){
if(i%j==0){
flag=1;
break;
}
}
if(flag==0){
cout<<i<<" ";
}
else flag=0;
}
return 0;
}