C++ find all prime numbers between 2-200
Prime number: refers to natural numbers greater than 1, except for 1 and itself (2 factors), which have no other factors
Problem solving ideas
Let mmm is 2~m \sqrt mmDivide if mmm cannot be 2~m \sqrt mmDivide any integer between, you can determine mmm is a prime number.
Some friends may ask why it is to m \sqrt mmNot to mmWhat about m ?
Then I will explain to my friends, the
formula ① nnn= m \sqrt m m × m \sqrt m m
Formula ② nnn= n n n ×1
herennThe factor of n ism \sqrt mmAnd 1 and itself, a total of 3 factors, so we only need to calculate to m \sqrt mmThat's it!
Problem solving ideas
To record mmWhether m is a prime number can be represented by a boolean variable (bool)pr. Set pr to true (true) at the beginning of the loop, ifmmm is divisible by an integer, it meansmmm is not a prime number, and the value of pr becomes false (false) at this time. Finally, according to whether the value of pr is true, decide whether to outputmmm . Wherennn is used to represent the number of prime numbers.
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
int m, k, i, n = 0;
bool pr;
for (m = 2; m <= 200; m = m + 1)
{
pr = true;
k = int(sqrt(m));
for(i=2;i<=k;i++)
if (m % i == 0)
{
pr = false;
break;
}
if (pr)
{
cout << setw(5) << m;
n = n + 1;
if (n % 5 == 0)cout << endl;
}
}
cout << "\n1-200的素数有:" << n << "个!" << endl;
cout << endl;
system("pause");
return 0;
}
Program analysis
When found mmAfter m is divisible by an integer,mmcan be judgedm is not a prime number, it is not necessary to continue to checkmmWhether m will be divisible by other integers, so use break to end the loop early. The if statement on line 19 checks whether pr is true, ifmm inthis loopm is never divisible by any integer, pr keeps its true at the beginning of the loop, so the prime numbermmshould be outputm . Then we know that even numbers are not prime numbers (including at least 1 and itself, but also 2 and another factor), so at the end of this loop letmmThe value of m +2, then use the same method to detect the newmmWhether m is a prime number.