[C Language] N code forms of prime numbers

 The words written in front

Hello everyone, my name is Xiaoxie. I hope it will be helpful to you after reading this. If there are any shortcomings, please criticize and correct me!

I hope I can share my learning and progress with you all!

Introduction

Everyone knows: " Prime numbers are also called prime numbers. A natural number greater than 1. A number that cannot be divided by other natural numbers except 1 and itself is called a prime number. Then if we If you want to know what the prime numbers between 1 and 200 are, how can you use C language to solve this problem?

One Arithmetic explanation------Trial division method

Trial division is a simple and intuitive method for determining prime numbers. The basic idea is: for a positive integer n, if n can be divided by any integer between 2 and n-1, then n is not a prime number; otherwise, n is a prime number.

The following is a C language implementation based on the trial division algorithm:

​
#include<stdio.h>
#include<math.h>
int main()
{
	int n = 0;
	int count1 = 0;//计算素数个数
	for (n = 100; n <= 200; n++)
	{
		
		int j = 0;
		for (j = 2; j <n; j++)
		{
			if (n % j == 0)//说明有除n和n本身的其他数整除,说明i不是素数
				break;
		}
			if (j ==n)//说明2到n-1中没有n的因子
			{
				printf("%d\n", n);
				count1++;
			}
			

	}printf("\ncount1=%d", count1);
	return 0;

}

​

To know the time complexity of the above, we can see how many times it loops. We can add a monitoring of the number of loops to the above code, so that we can intuitively understand whether this code is efficient or not.

The code is implemented as follows:

#include<stdio.h>
#include<math.h>
int main()
{
	int n = 0;
	int count1 = 0;//计算素数个数
	int count2 = 0;//计算循环次数
	for (n = 100; n <= 200; n++)
	{
		
		int j = 0;
		for (j = 2; j <n; j++)
		{
			count2++;
			if (n % j == 0)//说明有除n和n本身的其他数整除,说明i不是素数
				break;
		}
			if (j ==n)//说明2到n-1中没有n的因子
			{
				printf("%d\n", n);
				count1++;
			}
			

	}printf("\ncount1=%d", count1);
	printf("\ncount2=%d", count2);
	return 0;

}

From this we can conclude that this code loops 3292 times with only 100 numbers, and we judge whether an algorithm is good or bad by seeing whether it is efficient and whether its execution efficiency is efficient. So we should optimize it.

Optimized version of trial division--square root

n=a*b, for example, 16=2*8=4*4, which means that there is at least one number in a and b <= square root n. If a number that can divide i is not found before the square root, it will not It is possible to find other numbers that divide i, then the number is a prime number. The following is the code implementation:

#include<stdio.h>
#include<math.h>
int main()
{
	int n = 0;
	int count1 = 0;//计算素数个数
	int count2 = 0;//计算循环次数
	for (n = 100; n <= 200; n++)
	{
		int j = 0;
		for (j = 2; j <= sqrt(n); j++)//使用sqrt库函数要引用#include<math.h>
		{
			count2++;
			if (n % j == 0)//说明有除n和n本身的其他数整除,说明i不是素数
				break;
		}
			if (j>sqrt(n))//说明2到根号n中没有n的因子
			{
				printf("%d\n", n);
				count1++;
			}
			

	}printf("\ncount1=%d", count1);
	printf("\ncount2=%d", count2);
	return 0;

}

From the above code, we greatly optimize the execution efficiency of the algorithm and reduce the time for the program to implement functions.

Optimized version of trial division--Removing even numbers

From the definition of prime numbers, we know that prime numbers can only be divisible by 1 and itself, so as long as n is an even number, it must not be a prime number. From this, we can exclude some numbers from the source. The following is the code implementation:

#include<stdio.h>
#include<math.h>
int main()
{
	int n = 0;
	int count1 = 0;//计算素数个数
	int count2 = 0;//计算循环次数
	for (n = 100; n <= 200; n++)
	{
		if (n % 2 == 0)//判断n是否为偶数
		{
			
			continue;
		}
		int j = 0;
		for (j = 2; j <= sqrt(n); j++)//使用sqrt库函数要引用#include<math.h>
		{
			count2++;
			if (n % j == 0)//说明有除n和n本身的其他数整除,说明i不是素数
				break;
		}
			if (j>sqrt(n))//说明2到根号n中没有n的因子
			{
				printf("%d\n", n);
				count1++;
			}
			

	}printf("\ncount1=%d", count1);
	printf("\ncount2=%d", count2);
	return 0;

}

It can be seen that count2=342, only 342 are cycled, which reduces the time for the program to implement functions and improves efficiency. Therefore, the blogger strongly recommends that everyone master this method. In this way, when you do a question with other people, you will directly separate yourself from others. So there is only one algorithm for judging prime numbers. Next, the blogger will introduce an algorithm to you.

fourEratosthenes screening method

Sometimes, in addition to testing whether a given integer x is a prime number function, if we can prepare a prime number sequence or prime number table in advance, it can help us solve prime number related problems more effectively.
The Sieve of Eratosthenes can quickly enumerate all prime numbers within a given range. This algorithm generates a prime number table in the following steps.
Eratosthenes screening method:

  1. List integers greater than or equal to 2.
  2. Leave the smallest integer 2, delete all multiples of 2.
  3. Leave the smallest 3 among the remaining integers and delete all multiples of 3.
  4. Leave the smallest 5 among the remaining integers and delete all multiples of 5.
  5. The same applies to the following, leaving the smallest integer that has not been deleted, deleting multiples of this integer, and looping until the end.

Taking the smallest 4 prime numbers as an example, the solution process is as shown in the figure.
Original table:

First round:Second round:

Round 3:

The fourth round:According to the ideas provided in the above table, we can use C language to implement the application of this algorithm

code show as below:

​
#include <stdio.h>
#include <stdbool.h>

#define MAX 200

// 判断一个数是否为素数
bool is_prime(int num) {
    if (num < 2) { // 如果一个数小于2,那么它不是素数
        return false;
    }
    for (int i = 2; i * i <= num; i++) { // 遍历2到num的平方根
        if (num % i == 0) { 
            // 如果num能被i整除,那么它不是素数
            return false;
        }
    }
    return true; // 如果num不能被2到它的平方根之间的任何数整除,那么它是素数
}

// 使用埃拉托色尼筛选法找出1到MAX之间的所有素数
void sieve_of_eratosthenes() {
    bool is_prime[MAX + 1]; // 创建一个布尔类型的数组,用于存储1到MAX之间的所有数是否为素数
    for (int i = 2; i <= MAX; i++) { // 将所有数初始化为素数
        is_prime[i] = true;
    }
    int count = 0; // 记录循环次数
    for (int i = 2; i * i <= MAX; i++) { // 遍历2到MAX的平方根
        if (is_prime[i]) { // 如果i是素数
            for (int j = i * i; j <= MAX; j += i) { // 将i的所有倍数标记为非素数
                is_prime[j] = false;
            }
            count++; // 执行了一个完整的循环
        }
    }
    printf("循环次数: %d\n", count); // 打印循环次数
    for (int i = 2; i <= MAX; i++) { // 打印所有素数
        if (is_prime[i]) {
            printf("%d ", i);
        }
    }
}

// 主函数
int main() {
    sieve_of_eratosthenes();
    return 0;
}

​

The Eratosthenes screening method requires a portion of memory space (proportional to the maximum value N of the integers to be tested), but its complexity is only O(N log log N).

Summarize

There are many kinds of algorithms that can solve prime numbers. There is an old saying that "live and learn". C language is a language that requires continuous learning and continuous design of better solutions. I hope this article can help you understand C We provide a little help with language learning. Please forgive me for any shortcomings. Let us learn and grow together.

Guess you like

Origin blog.csdn.net/xiaoxie8023/article/details/133691551