Prime Number, also known as a 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.
I. Solve the problem according to definition: it is also the most stupid method with low efficiency:
package test.ms;public class FindPrime { // 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:
package test.ms;public class Prime { public static void main(String[] args) {for(int j = 2; j<1000; j++){if(m(j)){System.out.print(j+" ");}}}public static boolean m(int num){for(int j = 2; j<=Math.sqrt(num);j++){if(num%j == 0){return false;}}return true;}}
3: Find the rule (from a Forum)
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.
Package test. ms; import Java. util. arraylist; import Java. util. list; public class primes {public static void main (string [] ARGs) {// calculate the prime number 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 () ;}}/ *** evaluate all prime numbers within n ** @ Param N range ** @ return all prime numbers within N */privat E 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 feature of a prime number: only 2 of all prime numbers is an even number. If a number can be divisible by its previous prime number, it is not a prime number.