PAT Class B Java Implementation_1007. Prime Pair Conjecture_With Detailed Problem Solving Notes_07

1007. Prime Pair Conjecture (20)

time limit
400 ms
memory limit
65536 kB
code length limit
8000 B
Judgment procedure
Standard
author
CHEN, Yue

Let us define d n  as: d n  = p n+1  - p n , where p i  is the ith prime number. Clearly there is d 1 =1 and d n  is even for n>1. The "prime pair conjecture" states that "there are infinitely many pairs of adjacent prime numbers that differ by 2".

Now given any positive integer N (< 10 5 ), count the number of prime pairs that satisfy the conjecture not exceeding N.

Input format: Each test input contains 1 test case, giving a positive integer N.

Output format: The output of each test case occupies one line, and does not exceed the number of N prime pairs that satisfy the conjecture.

Input sample:
20
Sample output:
4

----------------------------------------------------------------------------------------------------------------

/*The idea of ​​creating a prime number table:
 * Build an array, use the array index to represent the number, a value of 0 indicates that the number is not a prime number, and a value of 1 indicates that the number is a prime number.
 * Initialize the array and assign all elements in the array to 1
 * Traverse back from index 2 (0 and 1 are not prime numbers), as long as the value corresponding to the index is 1, assign its multiple index to 1.
*/
import java.util.Scanner;
import java.util.Arrays;
public class PAT_B_1007//The class name needs to be changed to Main on the PAT platform
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);
		int num = in.nextInt();//Receive the input number
		
		int[] prime = new int[100005];//Array representing prime numbers, the index corresponding to the value of 1 is a prime number
		Arrays.fill(prime,1);//Initialize the array to fill 1
		for(int i = 2; i < prime.length; i++)
		{//Start from index 2 and traverse backwards (0 and 1 are not prime numbers), as long as the value corresponding to the index is 1, assign its multiple index to 1.
			if(prime[i] == 1)
			{
				for(int j = i + i; j < prime.length; j=j+i)
					prime[j] = 0;
			}
		}
		
		int sum = 0;//calculate prime pairs
		for(int i = 2; i <= num-2; i++)
		{//Starting from 2 and traversing backwards, if the value corresponding to an index is 1, and the value corresponding to the cut index + 2 is also 1, it constitutes a pair of prime numbers
			if(prime[i] == 1 && prime[i+2] == 1)
				sum++;
		}
		
		System.out.println(sum);//Output the number of prime pairs
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326424535&siteId=291194637