Details of an IsPrime Algorithm

Source: Internet
Author: User

Details of an IsPrime Algorithm

//*******************************

//

// Written at the dormitory on Thursday, September 18, 2014

// Author: Xia hualin

//

//********************************

I haven't updated my blog for a long time. I have had a lot of troubles recently. I am a junior. I really have to sit down and read a book.

What I want to talk about today is a detailed problem caused by the IsPrime algorithm. The details I am talking about here are what I think. If there is anything wrong, I hope to correct it!

The implementation of a simple IsPrime algorithm is as follows:

 1 bool IsPrime(int n) 2 { 3 int i; 4  5 if(n % 2 == 0)return false; 6 for(i = 3; i <= sqrt(n); i += 2) 7 { 8 if(n%i == 0)return false; 9 }10  return true;11 }

This Code contains some serious errors. It is obvious that when the parameters are 1 and 2, the function will return an incorrect answer. To solve this problem, the simplest method is to check 1 and 2 separately. You can simply add them at the beginning of the function:

if(n <= 1)return false;if(n == 2)return true;

Another performance problem is that the IsPrime algorithm is designed to improve efficiency, but sometimes it takes longer time than the old one.

This problem exists in the control row of the for Loop:

for(i = 3; i <= sqrt(n); i += 2)

Although modern computers can calculate the square root within a relatively short period of time, it takes longer to calculate the square root than to execute simple arithmetic operations. In the program, sqrt (n) must be calculated every time a loop is executed, and n is the constant amount in the entire loop, so we calculate sqrt (n) for each loop) this is not so cost-effective. To avoid calling the sqrt () function again and again, you can calculate sqrt (n) before the loop and store it into a variable, for example:

double limit = sqrt(n);for(i = 3; i <= limit; i += 2)

This simple change will significantly improve the implementation efficiency of the IsPrime algorithm.

This IsPrime algorithm also has a difficult problem to identify. It is difficult to find this logical error because it may not appear in your thousands of test examples, for some special test examples, this implementation may produce the correct results on some machines and the incorrect answers on another machine.

To understand this problem, I think it is necessary to write another article on floating point numbers in computers. However, due to space limitations, I will not describe its principles here.

Strict equality of floating point numbers is a dangerous action. Suppose n is 49 and it is the square of 7. What will be returned when the computer calls the sqrt () function for 49?In a strict mathematical field, the square root is 7, but the computer does not work in this field. It returns only a floating point number close to 7.And the number may be 6.9999999999999999999. Although this number is close to 7, this difference is enough to affect the result of I <= limit.If I is 7 and limit is 6.999999999, the last cycle of the Loop will not be executed, the program will never check whether 7 can be divisible, and 7 is the only factor of 49, in this way, the program will incorrectly classify the 49-class Prime Number. On the other hand, if sqrt (49) returns 7.0 or 7.0000000001, The IsPrime algorithm will get the correct answer. Therefore, the correctness of this implementation depends on how the hardware executes the floating point calculation, and making the correctness of an algorithm dependent on the characteristics of the computer running it is a serious error. This problem can be easily solved. If the square root of n is smaller than a certain boundary, we always tend to check one more possible divisor to avoid any harm if we test one more divisor, we only pay a very small price to ensure that algorithms can be correctly executed on different hardware. Such a trade-off is quite cost-effective for us.

As long as the modification is simple:

double limit = sqrt(n) + 1;

The IsPrime algorithm is very simple, but the details are worth the attention.


Gao Yi mathematical algorithm 3

First of all, I assume that you want algorithms, not implementation. If you do not want to understand them correctly, otherwise you have to work for half a day.
Design a function IsPrime to determine whether the input is a prime number and enter a positive integer. If this number is returned (true), if not, 0 (false) is returned ), the call does not determine whether the return value is directly added or the sum value is not increased.
The IsPrime is added in a loop and does not need to be determined.
IsPrime: first, judge whether the input is an even number. If yes, return 0 and exit.
If no, search for the number of divisible values. The number must meet the following conditions: ① an odd number (step 2) ② a positive integer between 2 and the square root of the input. If yes, returns 0; otherwise, returns 0.

This is only based on general considerations. To solve this problem, we can call IsPrime from external control, first initialize and set the sum to 2, and start from 3 as the IsPrime input, and set the step size to 2, avoid entering an even number. In this way, the corresponding branches inside IsPrime can be removed, and no branches are added outside of IsPrime. In this way, the problem can be accelerated.

Yujian, for reference only,

By the way, do I study algorithms when I was a senior one? Study hard!

Compile a function named isprime () to determine whether a number is a prime number (that is, a prime number)

# Include <stdio. h>
# Include <math. h>
Int isprime (int n)
{
Int k = (int) sqrt (n );
For (int I = 2; I <= k; I ++)
{
If (n % I = 0)
Return 0;
}
Return 1;
}
Void main ()
{
Int;
Scanf ("% d", & );
If (isprime ())
Printf ("% d is a prime. \ n", );
Else
Printf ("% d is not a prime. \ n", );
}

Related Article

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.