Prime number Concept
A prime, also known as a prime number, refers to a number of natural numbers greater than 1 that cannot be divisible by other natural numbers except 1 and the integer itself (it can also be defined as a number of only 1 and two factors of itself). The smallest prime number is 2, and is the only even number in the prime number, and the other primes are odd . There are infinitely many prime numbers, so there is no maximum prime number.
At present, there are about 3 calculation methods in the summary, the following
1. Rude violence Definition Solution method
Public classPrime {//find the prime between 1 to +; Public Static voidMain (string[] args) {Printprime (1000); } Public Static voidPrintprime (intN) { for(inti = 2; I < n; i++) { intCount = 0; for(intj = 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 (reduce cycle times)
Public classPrime {//find the prime between 1 to +; Public Static voidMain (string[] args) { for(inti = 2; i < 1000; i++) { if(IsPrime (i)) {System.out.print ( I+ " "); } } } /*** To specify whether the number is prime *@paramnum *@return */ Public Static BooleanIsPrime (intnum) { for(intj = 2; J <= math.sqrt (num); J + +) { if(num% J = = 0) { return false; } } return true; }}
3. Law of Law
The smallest prime number is 2, and is the only even number in the prime number, and the other primes are odd. There are infinitely many prime numbers, so there is no maximum prime number.
Public classPrime {//find the prime between 1 to +; Public Static voidMain (string[] args) {List<Integer> primes = getprimes (1000); //Output Results for(inti = 0; I < primes.size (); i++) {Integer Prime=Primes.get (i); System.out.printf ("%8D", Prime); if(i% 10 = = 9) {System.out.println (); } } } /*** To find all primes within n *@paramN Range *@returnall primes within n*/ Private StaticList<integer> Getprimes (intN) {List<Integer> result =NewArraylist<integer>(); Result.add (2); for(inti = 3; I <= N; i + = 2) { if(!divisible (i, result)) {Result.add (i); } } returnresult; } /*** Determine if n can be divisible *@paramn the number to be judged *@paramprimes a list containing prime numbers *@returnreturns True if n can be divisible by any one of the primes. */ Private Static BooleanDivisible (intN, list<integer>primes) { for(Integer prime:primes) {if(n% Prime = = 0) { return true; } } return false; }}
The first and second are very simple methods:
The third method illustrates the characteristics of a prime number: in all prime numbers, only 2 is an even number. If a number can be divisible by the prime numbers before it, then this number is not prime.
Java Prime number Solver