C + + Code:prime decision

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.