The method of C language function to find prime number
Direct exhaustion
The idea of this method isn divides all the numbers from 2 to (n-1) respectivelyTo judge, if there is a remainder of 0, it is not a prime number, and if the remainder of all numbers is not 0, it is a prime number.
function:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int Prime(int num){
if (num <2){
//2是最小的素数所以直接排除更小的
return 0;
}
for (int i = 2; i <num; i++){
if (num%i == 0){
return 0;//能整除的就不是素数
}
}
return 1;// 素数得到
}
Demand 100-200 prime numbers:
int main()
{
int num = 0;
for (num = 100; num <= 200; num++){
//输入100-200的素数
if (Prime(num) == 1){
//函数中return 1的都是素数
printf("%d\n", num);
}
}
system("pause");
return 0;
}
Find if a number is prime:
int main()
{
int num = 0;
printf("输入一个数判断是否是素数:");
scanf("%d", &num);
int a=Prime(num);
if (a == 1){
printf("是素数");
}
else
printf("不是素数");
system("pause");
return 0;
}
Cut in half
Only the condition of the for loop is changed, which directly reduces the amount of calculation by half.
Because 2 is the smallest divisor, it is impossible for a number to be evenly divided after 1/2.
Note that there is an additional "=" sign at this time, which eliminates the square number.
int Prime(int num){
if (num <2){
return 0;
}
for (int i = 2; i <num; i++){
if (num%i == 0){
return 0;
}
}
return 1;
}
Change to:
int Prime(int num){
if (num <2){
return 0;
}
for (int i = 2; i <=num/2; i++){
//这里的for条件改变
if (num%i == 0){
return 0;
}
}
return 1;
}
Call the square root function
The condition of the for loop is also changed, so that more calculations are directly reduced.
Because the two divisors of a number must have a value less than or equal to its square root.
Note that there is an additional "=" sign at this time, which eliminates the square number.
Add the header file:
#include<math.h>
int Prime(int num){
if (num <2){
return 0;
}
for (int i = 2; i <num; i++){
if (num%i == 0){
return 0;
}
}
return 1;
}
Change to
int Prime(int num){
if (num <2){
return 0;
}
for (int i = 2; i <=sqrt(num*1.0); i++){
//这里引用了平方根函数sqrt
if (num%i == 0){
return 0;
}
}
return 1;
}
Supplement:
There is another optimization idea, except for 2 and 3, no two prime numbers are adjacent. So it can be i+=2. The premise is an odd number starts