Prime function in judgment, judge whether a number is prime, why in addition to that number long enough root

The following code to understand how that i <= sqrt (x) too!

#include<bits/stdc++.h>//万能头文件,拿走不谢。 
using namespace std;
bool isprime(int x) {
	if(x == 1)
		return false;
	for(int i = 2; i <= sqrt(x); i++)//是因为不是素数,必然是合数,合数必然是除1和本身之外的两个数相乘。 
		if(x % i == 0) return false;
	return true;
}
int main() {
	int n;
	cin >> n;
	for(int i = 0; i < n; i++) {
		int b;
		cin >> b;
		printf("%s\n", isprime(b) ? "Yes" : "No");
	}
	return 0;
}

Below we this number to 16, for example, the following operation

Here Insert Picture Description
16 is a composite number (and is in addition to their other than 1 can also be divisible and relatively prime)

16 is obtained by multiplying two factors, where factors can be written as 1 and 2 factor. (Such as purple word part)

6 3 * 4 * 4 = red painting under number 1 = 16 = 2 * 16 * 8 = 16 Videos are relatively small factor, that factor is always less than 1 is equal to the square root of 16.

The benefit of this

From 2 to start screening primes, as long as there is screening factor 1 it can prove that it could not divisible by a prime number. This saves a lot of computation, such as> number 10000, you were more than a hundred cycles can determine whether it is a prime number, and thus directly down to 100 from 10000.
Thus where efficient.

Released eight original articles · won praise 8 · views 206

Guess you like

Origin blog.csdn.net/xzy15703841578/article/details/105264168