Simple algorithm problem, prime number pair conjecture


Preface

I started to learn algorithms today, and I have never studied well before. But today, I finally understand the meaning of the algorithm.


1. Topic-Prime Number Pair Conjecture

Let us define d​n as: dn ​​=p ​(n+1) ​​−p ​n ​​, where p ​i ​​ is the i-th prime number. Obviously d ​1 ​​ =1, and d ​n ​​ is even for n>1. The "prime pair conjecture" believes that "there are infinitely many pairs of adjacent prime numbers with a difference of 2". Now given any positive integer N (<10 ​5 ​​ ), please count the number of prime number pairs that do not exceed N that satisfy the conjecture.

Second, the thinking

My initial idea was very simple, just find all the prime numbers directly, and then check whether the difference between each pair of prime numbers is 2. Find the prime numbers directly and exhaustively.

code show as below:

import java.util.Scanner;
public class test2 {
    
    
    public static void main(String[] args){
    
    
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        int b = 2;
        int c = 3;
        int num = 0;
        boolean z = true;
        for (int x = 3; x<=a ; x++){
    
    
            for(int y = 2;y<=x;y++){
    
    
                if(x%y==0){
    
    
                    z = false;
                    break;
                }
            }
            if(z){
    
    
                b = c;
                c = x;
                if (c - b == 2){
    
    
                    num++;
                }
            }
            z = true;
        }
        System.out.println(num);
    }
}

There is no problem with the function, but it timed out when checking the spelling. The reason is when the number is 10^5. It takes too long to check if a number is prime. At this moment I can do nothing.

amendment

After querying, judging whether a number is a prime number does not need to be exhaustive to itself. Just count to the square root. This saves a lot of calculation time in the later stage. Math.sqrt(x) can be used to calculate the square root in java. Therefore, the prime number judgment code is modified to the following.

            for(int y = 2;y<=Math.sqrt(x);y++){
    
    
                if(x%y==0){
    
    
                    z = false;
                    break;
                }
            }

to sum up

Today, I finally understand the meaning of algorithms for programs. Before, I only used my brains and felt like opening a door. Although it is just a simple topic, I still feel that it has benefited a lot. Just the first blog, as a memorial.

Guess you like

Origin blog.csdn.net/qq_43668890/article/details/114043764