This is the second day of my participation in the August Text Challenge.More challenges in August
Hello ah, I am gray little ape, a super will write bug program ape!
Welcome to my column.”The daily blue bridge”, the main role of this column is to share with you in recent years blue bridge cup provincial competition and the final and other real questions, analysis of the existing algorithm ideas, data structure and other content, to help you learn more knowledge and technology!
Title: Group prime numbers
Prime numbers are numbers that can no longer be divided equally, such as 2, 3, 5, 7, 11, etc
9=3*3 means that it can be divided into three equal parts and is therefore not prime
Our country was founded in 1949. If you were given only four cards with numbers 1, 9, 4 and 9, you could place them in any order you wanted.
So how many 4-digit primes can you form?
For example, 1949 and 4919 meet the requirements
Please e submit the number of 4-digit primes you can form. Do not list them!
Note: do not submit the solution process, or other supporting text
Key points of investigation:
Recursive and backtracking algorithms for the full arrangement of elements, prime number judgment, repeated elements to the weight
In this problem we need to focus on master is recursion, and backtracking algorithm under the whole arrangement of elements, according to the thought of 1, 9, 4, 9 this four number from the whole arrangement, access to the array as a result, and then judge the result of the arrangement, whether it is prime number, after record meet the requirements of prime Numbers.
Answer source:
Package 2013 Provincial competition import java.util.HashSet; import java.util.Set; public class Year2013_t2 { static Set<Integer> set = new HashSet<Integer>(); // Define the hash set, Public static void arrange(int[] arr,int n) {public static void arrange(int[] arr,int n) { If (n==arr.length) {int num =arr [0]*1000 + arr[1]*100 + arr[2]*10 + arr[3]; If (check(num)==num) {set.add(num); }} for (int I = n; i < arr.length; Int t = arr[n]; int t = arr[n]; arr[n] = arr[i]; arr[i] = t; arrange(arr, n+1); T = arr[n]; arr[n] = arr[i]; arr[i] = t; Private static int check(int num) {for (int I = 2;} private static int check(int num) {for (int I = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { return 0; } } return num; } public static void main(String[] args) {int[] array = {1,9,4,9}; arrange(array, 0); System.out.println(set.size()); // Output the required length of data stored in the collection}}Copy the code
Example output:
There are deficiencies or improvements, but also hope that small partners put forward messages, learn together!
Interested partners can pay attention to the column!
Grey ape accompany you to progress together!