Parsing: Prime is the natural number that cannot be divisible by other numbers except for the 1 itself. Obviously the smallest number is 2, and the remaining even numbers are not primes. For an odd-looking k, you need to test each odd number between 3~k-1, and once you find an odd j that can be divisible by K, K is not a prime; only if all the odd numbers in the specified range are tested, they cannot be divisible by K to determine if K is prime. In fact, the test range can be reduced to 3~sqrt (k). For example, to determine whether 97 is a prime number, the test range is all odd 3, 5, 7, 9 between 3~9.84.
The Java code is as follows:
Package Test;import Java.text.simpledateformat;import Java.util.date;public class prime{static Boolean isPrime (int k) c0/>//Boolean function, static method, class method {if (k==2) return true;if (k<2| | k>2&&k%2==0) return false;int j= (int) java.lang.Math.sqrt (k), if (j%2==0) j--; Get the maximum odd while (j>2 && k%j!=0) J-=2;return j<=1; in the test range If the value of J is less than or equal to 1 or j<2, it can be explained that K is prime }public static void Main (string[] args) {long starttime=system.currenttimemillis (); System.out.print ("2"); int n=1;int k;for (k=3;k<1000;k+=2) //test all odd if (IsPrime (k)) //test k is prime number { System.out.print (k + "); N++;if (n%20==0) System.out.println ();} System.out.println ("\nn=" +n); SimpleDateFormat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Set the date format System.out.println ("Current system time is:" +df.format (new Date ()));//new Date () to get the current system time long endtime= System.currenttimemillis (); SYSTEM.OUT.PRINTLN ("program Run Time:" + (Endtime-starttime) + "MS");}}
The C + + code is as follows:
#include <iostream> #include <cmath> #include <iomanip>using namespace Std;int main () {cout<< " 2 "<<SETW (5); int M,k,i,n=1;bool Prime; Defines the prime variable for (m=3;m<100;m+=2) //To determine if M is a prime number, m varies from 3 to 100, and increments to 2{prime=true;k=int (sqrt (m)); for (i=2;i<=k;i++) //The function of this loop is to divide m by 2~sqrt (m), to check if it can be divisible by the IF (m%i==0) {prime=false;break;} if (prime) {COUT<<SETW (5) <<m;n=n+1;} if (n%10==0) Cout<<endl;} Cout<<endl;return 0;}
Note: Friends can compare their similarities and differences (of course, the algorithm is the same way!) )
The similarities and differences between Java and C + + language programming the number of primes in the set range