Java prime number solution, java Prime Number
Concept of prime number
Prime Number, also known as prime number, refers to a natural number greater than 1, except for 1 and the integer itself, it cannot be divisible by other natural numbers (it can also be defined as the number of only one and two factors ). The smallest prime number is 2, which is the only even number in the prime number. Other prime numbers are odd. There are infinite prime numbers, so there is no maximum prime number.
At present, there are about three calculation methods to solve the problem, as shown below:
1. Definition of rude and violent solutions
public class Prime { // find the prime between 1 to 1000; public static void main(String[] args) { printPrime(1000); } public static void printPrime(int n) { for (int i = 2; i < n; i++) { int count = 0; for (int j = 2; j <= i; j++) { if (i % j == 0) { count++; } if (j == i && count == 1) { System.out.print(i + " "); } if (count > 1) { break; } } } }}
2. Square Root Algorithm (reducing the number of cycles)
Public class Prime {// find the prime between 1 to 1000; public static void main (String [] args) {for (int I = 2; I <1000; I ++) {if (isPrime (I) {System. out. print (I + "") ;}}/ *** determines whether the specified number is a prime number * @ param num * @ return */public static boolean isPrime (int num) {for (int j = 2; j <= Math. sqrt (num); j ++) {if (num % j = 0) {return false ;}} return true ;}}
3. Regular Law
The smallest prime number is 2, which is the only even number in the prime number. Other prime numbers are odd. There are infinite prime numbers, so there is no maximum prime number.
Public class Prime {// find the prime between 1 to 1000; public static void main (String [] args) {List <Integer> primes = getPrimes (1000 ); // output result for (int I = 0; I <primes. size (); I ++) {Integer prime = primes. get (I); System. out. printf ("% 8d", prime); if (I % 10 = 9) {System. out. println ();}}} /*** calculate all prime numbers within n * @ param n range * @ return all prime numbers within n */private static List <Integer> getPrimes (int n) {List <Integer> result = new ArrayList <Integer> (); result. add (2); for (int I = 3; I <= n; I + = 2) {if (! Divisible (I, result) {result. add (I) ;}} return result ;} /*** determine whether n can be divisible * @ param n number to be judged * @ param primes list containing prime numbers * @ return if n can be divisible by any of primes, returns true. */Private static boolean divisible (int n, List <Integer> primes) {for (Integer prime: primes) {if (n % prime = 0) {return true ;}} return false ;}}
Both the first and second methods are simple:
The third method illustrates the characteristics of a prime number: Of all prime numbers, only 2 is an even number. If a number can be divisible by its previous prime number, it is not a prime number.