PAT B1007 Prime number pair conjecture (out of 20)

Ideas:
Step 1: Find all prime numbers in the range.
Step 2: Determine whether two adjacent prime numbers differ by 2. If the difference is 2, the count is increased by 1.

Violent solution:
The following method is to solve all the prime numbers in the range of brute force without optimization, that is, the time complexity does not meet the requirements, the full score cannot be obtained, and a timeout will occur.

#include<iostream>

using namespace std;

int main()
{
    
    
	int N;
	cin >> N;
	int num[100000]; // 存储所有的
	int m = 0;
	for (int i = 2; i < N + 1; i++)
	{
    
    
		string s = "YES";
		for (int j = 2; j < i; j++)
		{
    
    
			if (i%j == 0) 
			{
    
    
				s = "NO";
				break;
			}
		}
		if (s == "NO") ;
		else num[m++] = i;
	}
	int count = 0;
	for (int i = 1; i < m; i++) 
	{
    
    
		if (num[i] - num[i - 1] == 2) count++;
	}
	cout << count;

	system("pause");
	return 0;
}

operation result:
Insert picture description here

After optimization:
that is, when solving prime numbers, the range of consideration is from 2 to radical i, so that the time complexity is reduced, and the full score AC can be achieved.

#include<iostream>
#include<math.h>

using namespace std;

int main()
{
    
    
	int N;
	cin >> N;
	int num[100000]; // 存储所有的
	int m = 0;
	for (int i = 2; i < N + 1; i++)
	{
    
    
		string s = "YES";
		for (int j = 2; j < sqrt(i)+1; j++)
		{
    
    
			if (i%j == 0) 
			{
    
    
				s = "NO";
				break;
			}
		}
		if (s == "NO") ;
		else num[m++] = i;
	}
	int count = 0;
	for (int i = 1; i < m; i++) 
	{
    
    
		if (num[i] - num[i - 1] == 2) count++;
	}
	cout << count;

	system("pause");
	return 0;
}

The specific areas of optimization:

for (int j = 2; j < sqrt(i)+1; j++)

Output result:
Insert picture description here

Post-code reflection: When
doing questions, if you have time requirements, you need to consider time complexity, and you must find ways to reduce time complexity.

Guess you like

Origin blog.csdn.net/qq_27538633/article/details/105921430