1 Determine if a number is prime
For determining whether a number m is a prime, the simplest way is to try dividing the integer from 2 to m-1, in terms of the number of primes, which must be prime if there is no exception to divide it.
1#include <iostream>2 using namespacestd;3 intMain ()4 {5cout <<"Please input a number:\n";6 intm;7CIN >>m;8 for(inti =2; I < M;++i)//i from 2 to M-19 if(m%i = =0)Ten { Onecout << M <<"is not a prime.\n"; A return 1; - } -cout << M <<"Is a prime.\n"; theCin.Get(); - return 0; - -}
Let's look at the following:
Mathematically, assuming that an integer m is not a prime number, it must be represented as a product of two factors:
So there must be a factor not less than the square root of M (that is, I). Therefore, whether M is a prime number, just try to divide the square root of M can be, do not have to m-1 (this paragraph must be understood). Therefore, the above program can be modified to:
1#include <iostream>2#include <cmath>3 using namespacestd;4 intMain ()5 {6cout <<"Please input a number:\n";7 intm;8CIN >>m;9 DoubleSqrtm = sqrt (m*1.0);Ten for(inti =2; i < Sqrtm; ++i) One if(m%i = =0) A { -cout << M <<"is not a prime.\n"; - return 1; the } -cout << M <<"Is a prime.\n"; -Cin.Get(); - return 0; +}
This takes a floating-point (double) variable, SQRTM, whose value is the square root of M, which is called a C + + library function sqrt, which is described in Cmath. Since I is an integer, I can only take the largest integer that is less than or equal to Sqrtm in inequality I<=sqrtm.
Modified program, the efficiency of a number of improvements. For example, to determine whether 101 is a prime number, originally to try to remove from 2 to 100, now as long as the 2 try to remove to 10 on the line.
C + + Code:prime decision